Saturday, June 25, 2016

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

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"



public String allStar(String str) {
 
    if(str==null||str.length()==0)
    {
      return str;
    }
    StringBuilder sb1 = new StringBuilder();
    StringBuilder strCopy = new StringBuilder(str);
    return appendStar(strCopy,sb1,0).toString();
   
}


StringBuilder appendStar(StringBuilder strCopy,StringBuilder sb1, int index)
{
  if(index==strCopy.length())
  {
    return sb1;
  }
 
    sb1.append(strCopy.charAt(index));
    if(index<strCopy.length()-1)
      sb1.append("*");
  return appendStar(strCopy,sb1,index+1);
}

No comments:

Post a Comment