Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete duplicates in a string using recursion?

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?

like image 875
JURO312 Avatar asked Feb 14 '26 09:02

JURO312


1 Answers

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); 
}
like image 191
CMPS Avatar answered Feb 15 '26 23:02

CMPS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!