0

compute recursively a
new string where adjacent characters that
are the same have been reduced to a single
character. So "yyzzza" yields "yza".
You must not use loops.
Here are some more examples:

string_clean("yyzzza") returns "yza"
string_clean("abbbcdd") returns "abcd"
string_clean("Hello") returns "Helo"


please give me some suggestion.

3
Contributors
5
Replies
6
Views
6 Years
Discussion Span
Last Post by Clinton Portis
Featured Replies
  • How about a skeleton : [code] string uniqify(const std::string& source,int currentLocation){ if(source.length() <= 1) return source; else{/*code here */} } string string_clean(const std::string& str){ return uniqify(source,0); } [/code] Read More

1

How about a skeleton :

string uniqify(const std::string& source,int currentLocation){
 if(source.length() <= 1) return source;
 else{/*code here */}
}
string string_clean(const std::string& str){
 return uniqify(source,0);
}

Edited by firstPerson: n/a

1
string string_clean(const string& str)
{
    if(str.length() == 0) return "";

    if(str[1] == str[0]) return str[0] + string_clean(str.substr(2));
    else return str[0] + string_clean(str.substr(1));
}

my code fail when the char appear 3 times

0

No you need to check if the current index location has the same value as the previous location and repeat until the end of string

0

i am kinda confused, can you be more specific please, this is raelly urgent.

0

suggestion:

//function prototype
string unique_chars(string line, int index = 0);
//function definition
string unique_chars(string line, int index)
{
     int pos = 0;
     string temp;
     
     //recusive exit case
     if(index == line.size())
     {
           return line;
     }

     pos = line.find(line[index], index+1)

     //if no other matching characters in string, move on to the next character
     if(pos == string::npos)
     { 
          return unique_chars(line, index++);
     }
     
     //erase a matching character, then move on to the next character
     else
     {
          line.erase(line.begin()+ pos);
          return unique_chars(line, index++);
     }
}

This is untested code. I just made it up. I don't know if this compiles without error. But you have to admit it's awesome help even if it doesn't work. It's sole intention is to give you an idea.. steer ye' in the right direction. What I would like to see from you now is a show of effort on your part.

Here is a decent youtube on "intro to c++ recursion": http://www.youtube.com/watch?v=kwFMkruKI8Y&feature=related

Here is a list of string class member functions: http://www.cplusplus.com/reference/string/string/

Edited by Clinton Portis: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.