-3

I can't understand this recursive method as the return method doesn't seem to add the charAt(0) method per run.

Suppose you were given a method that reverses a String (it is correct):

 public String reverseString(String s) {
        if (s.length() <= 1) 
             return s;

        return reverseString(s.substring(1)) + s.charAt(0);
    }

EDIT: I now understand:

  • rs(Hello)
  • rs(ello) + H
  • (rs(llo) + e) + H
  • ((rs(lo) + l) + e) + H
  • (((rs(o) + l) + l) + e) + H
  • o + l + l + e + H
Jebathon
  • 4,310
  • 14
  • 57
  • 108
  • 1
    Notice that you're only passing `s.substring(1)`, and not `s.substring(1) + s.charAt(0)` to the recursive invocation. – Rohit Jain Mar 15 '14 at 17:13
  • FYI this is a *horribly inefficient* way to reverse a string. It has to do a string concatenation (which constructs a new string object) at each level of the recursion. Using a `StringBuilder` would be much more efficient. – DaoWen Mar 15 '14 at 17:21
  • I found a duplicate (with same answer) http://stackoverflow.com/questions/9723912/reversing-a-string-recursion-java – Jebathon Mar 15 '14 at 17:36

1 Answers1

2

It is :

 rs(Hello)
 rs(ello) + H
 (rs(llo) + e) + H
 ((rs(lo) + l) + e) + H
 (((rs(o) + l) + l) + e) + H
 o + l + l + e + H
Piotr Gwiazda
  • 12,080
  • 13
  • 60
  • 91