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