I have been working with recursion lately and have come across a problem I cannot solve yet.
I'm am to return a string with all repeating adjacent characters removed, while leaving 1 copy of that repeating character.
I have the following:
public String stringClean(String str) {
if( str.length() < 2 )
return str;
if( str.charAt(0) == str.charAt(1))
return "" + str.charAt(0) + stringClean(str.substring(2));
return str.charAt(0) + stringClean(str.substring(1));
}
Of course, this only works when there are no more than 2 repeats of a character.
I know that if str.charAt(0) == str.charAt(1), then str.charAt(0) could possibly equal charAt(2),(3)...(4), etc.
So I'm assuming my problem is in the line:
return "" + str.charAt(0) + stringClean(str.substring(2));
// more specifically stringClean(str.substring(2));
Can I get an idea on where to head with this?