I have a trouble of understanding the calling stack of reverse a string use follow code:
public static String reverseString(String str) {
String reverse = "";
if (str.length() == 1) {
return str;
} else {
reverse += str.charAt(str.length() - 1) + reverseString(str.substring(0, str.length() - 1));
return reverse;
}
}
You can see the stack build up from 1 to 4 and then pop from 4 to 1. Take str = "abcd" as an example. It should returns "a" first (since "a" pop from calling stack firstly) which does not reverse a string. Am I getting something wrong here? thanks!


new StringBuilder(str).reverse().toString()