简体   繁体   English

charAt如何反转此方法中的输入?

[英]How does charAt reverse the input in this method?

//method
public static String foo(String s)

{
if (s.length() == 1)

return s;

else

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

What does foo(“abcd”) evaluate to? foo(“abcd”)评价的是什么? It is is my understanding that this would reverse the input, but why is that? 我的理解是这会扭转输入,但为什么呢?

You are facing recursion here! 你在这里面临递归

Each level of the recursion is appending the first character to the end, and invoke a recursive call on the suffix of the string. 递归的每个级别都将第一个字符附加到结尾,并在字符串的后缀上调用递归调用。

In your example, the call stack will look something like that: 在您的示例中,调用堆栈看起来像这样:

s = "abcd" => append 'a' to the end, and invoke on "bcd".
s = "bcd" => append 'b' to the end, and invoke on "cd".
s = "cd" => append 'c' to the end, and invoke on "d".
s= = "d" => return "d" as it is.

when you go back from the recursion, you actually append it in reverse order: 当你从递归回来时,你实际上是以相反的顺序追加它:

return "d"
return "d" + 'c' (="dc")
return "dc" + 'b' (="dcb")
return "dcb" + 'a' (="dcba")

Hope this makes it clear how the recursion works in this case: 希望这清楚地表明递归在这种情况下是如何工作的:

foo("bcd") + "a"
  (foo("cd") + "b") + "a"
    ((foo("d") + "c") + "b") + "a"
      (("d" + "c") + "b") + "a" -> "dcba"

It is a recursive reverse. 这是一个递归逆转。 s.substring(1) is the line without its first character; s.substring(1)是没有第一个字符的行; s.charAt(0) is the first character. s.charAt(0)是第一个字符。

What the function is saying is "if the line is one character long, the answer is the line itself; otherwise, chop off the first character, compute the same function, and add the chopped off character to the end of the result". 函数所说的是“如果行是一个字符长,则答案是行本身;否则,删除第一个字符,计算相同的函数,并将截断的字符添加到结果的末尾”。

You can work out on a piece of paper how performing the steps above amounts to reversing a string. 你可以在一张纸上解决如何执行上述步骤相当于反转字符串。

EDIT : It is worth noting that this implementation is going to crash with an exception if you try passing it an empty string. 编辑:值得注意的是,如果您尝试将其传递为空字符串,则此实现将以异常崩溃。 Changing if (s.length() == 1) to if (s.length() == 0) would address this problem (thanks to Tom Hawtin - tackline for mentioning this in a comment). if (s.length() == 1)更改为if (s.length() == 0)将解决此问题(感谢Tom Hawtin - 在评论中提及此问题)。

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

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