2017-11-18 123 views
3

我正在使用遞歸功能來刪除字符串中的重複字符。問題是,我不知道如何繼續傳遞一個字符串,以保持比較相鄰字符而不用切斷字符串。這是我到目前爲止有:如何使用遞歸刪除字符串中的重複項?

string stringClean(const string& str) 
{ 
    string s1 = str; 

    if (/*first char == next char*/) 
     s1.at(/*first char*/) = ""; 
     return stringClean(s1); 
    else 
     return s1; 
} 

舉個例子,stringClean( 「yyzzza」)應該返回 「YZA」。我應該如何繼續的任何提示?

+0

是重複的總是相鄰? – 0x499602D2

+0

是的。預期結果的其他示例如下: – JURO312

+0

stringClean(「abbbcdd」)→「abcd」 stringClean(「Hello」)→「Helo」 – JURO312

回答

1

C++

這就是我就是想

#include <iostream> 
#include <string> 

std::string rec(std::string &word, int index); 
std::string rec(std::string word) { 
    if(word.length() <= 1) { 
     return word; 
    } 
    return word[0] + rec(word, 1); 
} 

std::string rec(std::string &word, int index) { 
    if(index == word.length()) { 
     return ""; 
    } 
    return (word[index] != word[index-1] ? std::string(1, word[index]) : "") + rec(word, index+1); 
} 

int main() { 
    std::cout << rec("aaabbbbcccddd") << std::endl; 
} 

對於一行遞歸的戀人:

std::string rec(std::string &word, int index) { 
    return index == word.length() ? "" : (word[index] != word[index-1] ? std::string(1, word[index]) : "") + rec(word, index+1); 
} 
+0

不錯。現在用C++替換Java,請... – Fureeish

+0

你是對的:') – CMPS

相關問題