public static void main(String args[]) {
System.out.println(reverseString("His"));
}
public static String reverseString(String s) {
if (s.length() <= 1) {
return s;
} else {
char c = s.charAt(0);
return reverseString(s.substring(1)) + c;
}
}
Can someone explain me in details how this method works
I think the best way to understand how these types of methods work is to go through them by hand once with a simple example. Let's take the string "abc" and consider what happens when we call
reverseString("abc")
On the first iteration, we consider the else block (since "abc".length() is not less than or equal to 1). The method returns
reverseString("abc".substring(1)) + "abc".charAt(0)
which is equivalent to
reverseString("bc") + 'a'
Now we must consider reverseString("bc"). Again, we find ourselves in the else block, the method will return
reverseString("bc".substring(1)) + "bc".charAt(0)
which is equivalent to
reverseString("c") + 'b'
Evidently, reverseString("c") is just "c" - so reverseString("bc") is "cb" which, by above, means that reverseString("abc") is "cb" + 'a' which gives us "cba", as expected.
To summarize, we are essentially doing something like this:
reverse("abc")
reverse("bc") + 'a'
reverse("c") + 'b' + 'a'
"cba"
With a 4 character string:
reverse("abcd")
reverse("bcd") + 'a'
reverse("cd") + 'b' + 'a'
reverse("d") + 'c' + 'b' + 'a'
"dcba"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With