Java > Recursion-1 > stringClean (CodingBat Solution)

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"


Solution:

public String stringClean(String str) {
  if (str.length() < 2) return str;
  if (str.charAt(0) == str.charAt(1))
    return stringClean(str.substring(1));
  else
    return str.charAt(0) + stringClean(str.substring(1));
}


1 comment :

  1. public String stringClean(String str) {
    if(str.length() <= 1){
    return str;
    }
    return (str.charAt(0) != str.charAt(1))?
    str.charAt(0) + stringClean(str.substring(1))
    : stringClean(str.substring(1));
    }

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact