Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

method to reverse a string using recursion [closed]

Tags:

java

recursion

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

like image 810
Lexy Feito Avatar asked Mar 19 '26 13:03

Lexy Feito


1 Answers

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" 
like image 81
arshajii Avatar answered Mar 21 '26 15:03

arshajii



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!