Java > Recursion-1 > stringClean (CodingBat Solution)


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"


public String stringClean(String str) {
  if (str.length() < 2) return str;
  if (str.charAt(0) == str.charAt(1))
    return stringClean(str.substring(1));
    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));


Follow Me

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


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?


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