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)); }
this code is not working
ReplyDeleteIt works moron
ReplyDeletebase case can just be if(str.length() <= 1) return str;
ReplyDeletemore efficient way to write the first line would be to state on line 2
ReplyDeleteif (str.length()<2)return str;
public String allStar(String str) {
ReplyDeletereturn (str.length()<=1?str : str.substring(0,1)+"*"+allStar(str.substring(1)) );
}
public String allStar(String str) {
ReplyDeleteif (str.length()<2)
return str;
return str.charAt(0)+"*"+allStar(str.substring(1));
}