Java > Recursion-1 > allStar (CodingBat Solution)

Problem:

Given a string, compute recursively a new string where all the adjacent chars are now separated by a "*".

allStar("hello") → "h*e*l*l*o"
allStar("abc") → "a*b*c"
allStar("ab") → "a*b"


Solution:

public String allStar(String str) {
  if (str.equals("") || str.length() == 1) return str;
  return str.charAt(0) + "*" + allStar(str.substring(1));
}


6 comments :

  1. base case can just be if(str.length() <= 1) return str;

    ReplyDelete
  2. more efficient way to write the first line would be to state on line 2
    if (str.length()<2)return str;

    ReplyDelete
  3. public String allStar(String str) {
    return (str.length()<=1?str : str.substring(0,1)+"*"+allStar(str.substring(1)) );
    }

    ReplyDelete
  4. public String allStar(String str) {
    if (str.length()<2)
    return str;

    return str.charAt(0)+"*"+allStar(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