I am stuck on this CodingBat recursion problem:
Given a string, return recursively a "cleaned" string where adjacent chars that are the same have been reduced to a single char. So "yyzzza" yields "yza".
stringClean("yyzzza") → "yza"
stringClean("abbbcdd") → "abcd"
stringClean("Hello") → "Helo"
I can solve it using loops, but this is not allowed since the problem is supposed so be solved using recursion. Is there any way to solve this problem without using a loop and using only recursion? No global variables, no loops. I even thought of encoding some information in the parameter but that would be cheating too I think.
My previous program had no while loop, and I could only get half of the answers right. Basically, when I called my function with the string parameter, I checked the first 2 characters. If they were the same, I would return the character and call the function again with a string two characters smaller. A string of 3 or 4 of the same consecutive characters would always defeat my algorithm however.
public String stringClean(String str) {
if (str.length() == 0)
return "";
if (str.length() > 1) {
int counter = 1;
char a = str.charAt(0);
char b = str.charAt(1);
if (a == b)
{
while (str.length() > 1)
{
a = str.charAt(0);
b = str.charAt(1);
if (a != b) break;
counter++;
str = str.substring(1);
}
return a + stringClean( str.substring(1) ) ;
}
}
return str.charAt(0) + stringClean (str.substring(1) );
}