Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Repeated Character - Recursion

807591Mar 25 2008 — edited Mar 25 2008
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?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 22 2008
Added on Mar 25 2008
14 comments
1,626 views