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" |
Solution1 :
public String stringClean(String str)
{
if(str.length()<2)
{
return "";
}
else if(str.charAt(0)==str.charAt(1))
{
return stringClean(str.substring(1));
}
else
{
return str.charAt(0)+stringClean(str.substring(1));
}
}
solution 2: with out using substring function
public String stringClean(String str)
{
String res = new String();
return clean(str,0);
}
public String clean(String str,int index)
{
if(str.length()-index<2)
{
return str.valueOf(str.charAt(index));
}
else if(str.charAt(index)==str.charAt(index+1))
{
return clean(str,index+1);
}
else
{
return str.charAt(index)+clean(str,index+1);
}
}
No comments:
Post a Comment