I'm working on a function that uses recursion in order to delete duplicate characters in a string. Problem is, I'm not sure how to keep passing a string along in order to keep comparing adjacent characters without cutting the string somehow. Here's what I have so far:
string stringClean(const string& str)
{
string s1 = str;
if (/*first char == next char*/)
s1.at(/*first char*/) = "";
return stringClean(s1);
else
return s1;
}
As an example, stringClean("yyzzza") should return "yza". Any tips on how I should proceed?
C++
Here's what I just thought about
#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;
}
For one line recursion lovers:
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With