Your problem is that:
reduce("baab") = 'b' + reduce("aab") = 'b' + reduce("b") = 'b' + 'b' = "bb"
You only look at your first character until you can’t immediately remove it anymore. Then you never look at it again, even if at some point afterwards you actually could remove it.
I suppose you could do something like this instead:
public static String reduce(String str){
if(str.equals(""))
return "Empty String";
if(str.length()<2)
return str;
if(str.charAt(0)==str.charAt(1))
return reduce(str.substring(2));
String rest = str.substring(1);
String reducedRest = reduce(rest);
if (rest.equals(reducedRest))
return str;
else
return reduce(str.charAt(0) + reducedRest);
}
It’s not great but it should show you the general idea. Now you only ignore the first char if you don’t change the rest. If you do change it, you need to look at the whole thing again.
1
solved Hackerrank string reduction