如何使用递归删除字符串中的重复项?

问题描述:

我正在使用递归功能来删除字符串中的重复字符。问题是,我不知道如何继续传递一个字符串,以保持比较相邻字符而不用切断字符串。这是我到目前为止有:如何使用递归删除字符串中的重复项?

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

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