有人能解释一下这个反转字符串的递归java方法吗?

a9wyjsp7  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(319)

所以我是大学三年级的学生,正在努力理解递归。我理解一般的概念,但不理解它是如何正确实施的。我发现这段代码非常简单,似乎无法理解最后一行(递归)是如何工作的。任何帮助和解释都会很棒,谢谢(期末考试也快到了,我紧张吗

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

5ktev3wc1#

递归过程使用substring逐个删除字符,因为substring取一个开始索引,在1中,如果字符串是“”,那么是“”。substring(1)则substring将返回“bc”,因此在您的情况下,reverse是用substring处理的让我们输入“d”作为反向方法
然后进程会喜欢用反向方法作为递归

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

一旦reverse方法到达isempty语句,s.charat(0)将开始,它将在reverse方法的返回输出的末尾添加,这样它就修改了如下输出

d
dc
dcb
dcba

所以整个过程会像:

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

相关问题