简体   繁体   中英

Can someone explain this recursive Java method that reverses a string?

so I'm a junior in college trying to understand recursion. I understand the general concept but not how it's properly implemented. I found this extremely simple code and just can't seem to grasp how the last line (recursion) works. Any help and explanation would be awesome, thanks! (also finals coming up soon and boy am I nervous)

public static String reverse(String s) {
    if (s.isEmpty())
        return s;
    return reverse(s.substring(1)) + s.charAt(0);
}

Recursion process removing one by one char using substring, as substring take a beginning index which in 1 in you case so if our string is "ABC" then "ABC".substring(1) then substring will return "BC" So in your case reverse is processing with substring lets take our input is "abcd" for reverse methos

then process will like with reverse method as a recursion

bcd -> 1st reverse will call with this value
cd -> then reverse will call with cd
d -> then reverse will call with d
"" -> then reverse will call with "" as its blank string so reverse will terminate

once reverse method reach isEmpty statement the s.charAt(0) will start which will add at then end of return output from reverse method so it modified output like

d
dc
dcb
dcba

so whole process will like:

input to reverse method :bcd
input to reverse method :cd
input to reverse method :d
input to reverse method : "" empty string
result received from reverse method  
After modified result with return value from reverse method and charAt(0) operation : d
result received from reverse method  d
After modified result with return value from reverse method and charAt(0) operation : dc
result received from reverse method  dc
After modified result with return value from reverse method and charAt(0) operation : dcb
result received from reverse method  dcb
After modified result with return value from reverse method and charAt(0) operation : dcba

Here is an iterative version of the same algorithm for clarity, which iterates through the characters of the string in encounter order and concatenates them into a new string in reverse order , swapping the summands:

public static String reverse(String str) {
    String revStr = "";
    for (char ch : str.toCharArray()) {
        revStr = ch + revStr;
    }
    return revStr;
}
public static void main(String[] args) {
    System.out.println(reverse("some text string"));
}

Output:

gnirts txet emos

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM