private static String invertirPalabra(String palabra) {
String res = "";
if(palabra.length()==0){
res = palabra;
}else{
res = invertirPalabra(palabra.substring(1)+ palabra.charAt(0));
}
return res;
}
When doing this method of inverting a word, I get the StackOverFlow error. I guess it must have gone off the chain or something, but I don't know exactly what the error is.
Exception in thread "main" java.lang.StackOverflowError at java.lang.String.<init>(Unknown Source) at java.lang.String.substring(Unknown Source) at Ejemplo2.invertirPalabra(Ejemplo2.java:70)
Problem. Before we get to the answer, let's look at this call you're making:
If the word had 10 characters, it would be recursively calling the function with a long string ........
Can you see the problem now?
Yes, 10 characters too!!!... In other words, the recursive calls for
invertirPalabra("abc")
would be:Clearly the condition will never be met
if(palabra.length()==0){
.We did not reduce any characters in the recursive call. That should be the idea, right?
Well, that's the problem.
Solution. What if we recursively call the function with only what remains to be reversed ?
Thus, to
invertirPalabra("abc")
achieve:Code:
demonstration:
http://ideone.com/iXj5az
Extra. If you are interested in shortening the code a bit more:
if it is about recursion, then we must consider the base case and recursive case well:
I better explain it with an image
in code it would be:
Recursive Solution:
Non-recursive solution using the StringBuilder Class: