简体   繁体   English

Java递归简单字符串

[英]Java recursion simple string

The below code works just fine, it reverses a string.But, I do not understand how it works.下面的代码工作得很好,它反转了一个字符串。但是,我不明白它是如何工作的。 I think it should return an empty string since each time we are calling reversedString(sub);我认为它应该返回一个空字符串,因为每次我们调用reversedString(sub); it takes out the character at index 0, so we should end up with an empty string at the end.它取出索引 0 处的字符,所以最后我们应该得到一个空字符串。

import components.simplewriter.SimpleWriter;
import components.simplewriter.SimpleWriter1L;


public final class HelloWorld {




    private static String reversedString(String s) {
        if (s.length() == 0) {
            return s;
        } else {
            String sub = s.substring(1);
            String revSub = reversedString(sub);
            String result = revSub + s.charAt(0);
            return result;
        }
    }


    public static void main(String[] args) {
        SimpleWriter out = new SimpleWriter1L();
        out.println(reversedString("Banana"));

        out.close();
    }

}

I've heard you like visualizations:我听说你喜欢可视化:

reversedString("Banana");
\----------------------/
          |
    /---------------------------\
    reversedString("anana") + "B";
    \---------------------/
              |        
        /--------------------------\
        reversedString("nana") + "a" + "B";
        \--------------------/
                  |
            /-------------------------\
            reversedString("ana") + "n" + "a" + "B";
            \-------------------/
                      |
                /------------------------\
                reversedString("na") + "a" + "n" + "a" + "B";
                \------------------/
                          |
                    /-----------------------\
                    reversedString("a") + "n" + "a" + "n" + "a" + "B";
                    \-----------------/
                              |
                        /----------------------\
                        reversedString("") + "a" + "n" + "a" + "n" + "a" + "B";
                        \----------------/
                                  |
                                 /-\
                                  "" 

Sometimes, it helps to just print the values rather than return them.有时,仅打印值而不是返回值会有所帮助。

reverse("Reversed");

    
public static void reverse(String s) {
    if (s.length() > 1) {
        reverse(s.substring(1));
        // returns will emerge from this location
        // just like any other return. After the
        // point at which the method was called. 
    }
    System.out.print(s.charAt(0));
}

prints印刷

desreveR

If you move the print statement to the first position in the method, it will print in normal order.如果将打印语句移动到方法中的第一个位置,它将按正常顺序打印。

The thing to remember is that for each call of the method, the previous value is stored on the call stack.要记住的是,对于方法的每次调用,前一个值都存储在调用堆栈中。 So when it eventually returns, each modification of the string is returned in the opposite order.所以当它最终返回时,字符串的每次修改都以相反的顺序返回。 So here is what happens if you change the method to the following:因此,如果您将方法更改为以下内容,将会发生以下情况:

public static void reverse(String s) {
    System.out.println("Entered method via call : s = " + s);
    if (s.length() > 1) {
        reverse(s.substring(1));
        // returns will emerge from this location
        // just like any other return. After the
        // point at which the method was called. 
    }
    // first time this point is reached
    // s only contains one character.
    System.out.println("Returning : s = " + s);
}

Prints印刷

Entered method via call : s = Reversed
Entered method via call : s = eversed
Entered method via call : s = versed
Entered method via call : s = ersed
Entered method via call : s = rsed
Entered method via call : s = sed
Entered method via call : s = ed
Entered method via call : s = d
Returning : s = d
Returning : s = ed
Returning : s = sed
Returning : s = rsed
Returning : s = ersed
Returning : s = versed
Returning : s = eversed
Returning : s = Reversed

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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