在 Java 中使用递归反转字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9723912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reversing a String with Recursion in Java
提问by Bob Sanders
Here is some Java code to reverse a string recursively.
下面是一些递归反转字符串的 Java 代码。
Could someone provide an explanation of how it works?
有人可以解释它是如何工作的吗?
public static String reverse(String str) {
if ((null == str) || (str.length() <= 1)) {
return str;
}
return reverse(str.substring(1)) + str.charAt(0);
}
I'm not understanding how this can possibly work.
我不明白这可能如何工作。
采纳答案by Dave Webb
The function takes the first character of a String - str.charAt(0)
- puts it at the end and then calls itself - reverse()
- on the remainder - str.substring(1)
, adding these two things together to get its result - reverse(str.substring(1)) + str.charAt(0)
该函数采用 String 的第一个字符str.charAt(0)
- 将其放在末尾,然后调用自身reverse()
- 在余数上 -str.substring(1)
将这两件事加在一起得到它的结果 -reverse(str.substring(1)) + str.charAt(0)
When the passed in String is one character or less and so there will be no remainder left - when str.length() <= 1)
- it stops calling itself recursively and just returns the String passed in.
当传入的 String 为一个字符或更少时,因此将没有余数 - 当str.length() <= 1)
- 它停止递归调用自身并仅返回传入的 String 。
So it runs as follows:
所以它运行如下:
reverse("Hello")
(reverse("ello")) + "H"
((reverse("llo")) + "e") + "H"
(((reverse("lo")) + "l") + "e") + "H"
((((reverse("o")) + "l") + "l") + "e") + "H"
(((("o") + "l") + "l") + "e") + "H"
"olleH"
回答by Dave
Run it through a debugger. All will become clear.
通过调试器运行它。一切都会明朗起来。
回答by Jon Skeet
You need to remember that you won't have just onecall - you'll have nestedcalls. So when the "most highly nested" call returns immediately (when it finds just "o"), the next level up will take str.charAt(0)
- where str
is "lo" at that point. So that will return "ol".
你需要记住,你不会只有一个调用——你会有嵌套调用。因此,当“最高嵌套”调用立即返回时(当它只找到“o”时),下一级将采用str.charAt(0)
- 那时str
“lo”在哪里。所以这将返回“ol”。
Then the nextlevel will receive "ol", execute str.charAt(0)
for itsvalue of str
(which is "llo"), returning "oll" to the next level out.
然后,下一个水平将收到“OL”,执行str.charAt(0)
用于其的值str
(这是“LLO”),返回“OLL”下一级进行。
Then the nextlevel will receive the "oll" from its recursive call, execute str.charAt(0)
for itsvalue of str
(which is "ello"), returning "olle" to the next level out.
那么下一个水平将收到来自它的递归调用的“OLL”,执行str.charAt(0)
了它的价值str
(这是“ELLO”),返回“欧莱”到一个新的水平了。
Then the finallevel will receive the "oll" from its recursive call, execute str.charAt(0)
for itsvalue of str
(which is "hello"), returning "olleh" to the original caller.
然后最后一级将收到来自它的递归调用的“OLL”,执行str.charAt(0)
了它的价值str
(这是“你好”),返回“2009东海生日贺”到原来的调用者。
It may make sense to think of the stack as you go:
边走边想堆栈可能是有意义的:
// Most deeply nested call first...
reverse("o") -> returns "o"
reverse("lo") -> adds 'l', returns "ol"
reverse("llo") -> adds 'l', returns "oll"
reverse("ello") -> adds 'e', returns "olle"
reverse("hello") -> adds 'h', returns "olleh"
回答by jzworkman
Because this is recursive your output at each step would be something like this:
因为这是递归的,所以每一步的输出都是这样的:
- "Hello" is entered. The method then calls itself with "ello" and will return the result + "H"
- "ello" is entered. The method calls itself with "llo" and will return the result + "e"
- "llo" is entered. The method calls itself with "lo" and will return the result + "l"
- "lo" is entered. The method calls itself with "o" and will return the result + "l"
- "o" is entered. The method will hit the if condition and return "o"
- 输入“你好”。该方法然后用“ello”调用自己并返回结果+“H”
- 输入“你好”。该方法使用“llo”调用自身,并将返回结果+“e”
- 输入了“llo”。该方法用“lo”调用自己,并将返回结果+“l”
- 输入“lo”。该方法使用“o”调用自身并返回结果+“l”
- 输入“o”。该方法将满足 if 条件并返回“o”
So now on to the results:
现在来看结果:
The total return value will give you the result of the recursive call's plus the first char
总返回值将为您提供递归调用的结果加上第一个字符
To the return from 5 will be: "o"
从 5 返回将是:“o”
The return from 4 will be: "o" + "l"
4 的返回将是:“o”+“l”
The return from 3 will be: "ol" + "l"
3 的返回将是:“ol”+“l”
The return from 2 will be: "oll" + "e"
2 的返回将是:“oll”+“e”
The return from 1 will be: "olle" + "H"
1 的返回将是:“olle”+“H”
This will give you the result of "olleH"
这会给你“olleH”的结果
回答by len
Take the string Hello and run it through recursively.
获取字符串 Hello 并递归运行它。
So the first call will return:
所以第一个调用将返回:
return reverse(ello) + H
Second
第二
return reverse(llo) + e
Which will eventually return olleH
哪个最终会回来 olleH
回答by PATRY Guillaume
The call to the reverce(substring(1)) wil be performed before adding the charAt(0). since the call are nested, the reverse on the substring will then be called before adding the ex-second character (the new first character since this is the substring)
将在添加 charAt(0) 之前执行对 reverce(substring(1)) 的调用。由于调用是嵌套的,因此将在添加前第二个字符(新的第一个字符,因为这是子字符串)之前调用子字符串的反向
reverse ("ello") + "H" = "olleH"
--------^-------
reverse ("llo") + "e" = "olle"
---------^-----
reverse ("lo") + "l" = "oll"
--------^-----
reverse ("o") + "l" = "ol"
---------^----
"o" = "o"
reverse ("ello") + "H" = "olleH"
--------^-------
reverse ("llo") + "e" = "olle"
------ ---^-----
reverse ("lo") + "l" = "oll"
--------^-----
reverse ("o") + "l" = "ol "
---------^----
"o" = "o"
回答by assylias
Run the code below - it prints:
运行下面的代码 - 它打印:
Step 0: ello / H
Step 1: llo / e
Step 2: lo / l
Step 3: o / l
Step 3 returns: ol
Step 2 returns: oll
Step 1 returns: olle
Step 0 returns: olleH
第0步:ello / H
第1步:llo / e
第2步:lo / l
第3步:o / l
第3步返回:ol
第2步返回:oll
第1步返回:olle
第0步返回:olleH
Code:
代码:
public class Test {
private static int i = 0;
public static void main(String args[]) {
reverse("Hello");
}
public static String reverse(String str) {
int localI = i++;
if ((null == str) || (str.length() <= 1)) {
return str;
}
System.out.println("Step " + localI + ": " + str.substring(1) + " / " + str.charAt(0));
String reversed = reverse(str.substring(1)) + str.charAt(0);
System.out.println("Step " + localI + " returns: " + reversed);
return reversed;
}
}
回答by Tom
run the following and you'll see what's going on:
运行以下命令,你会看到发生了什么:
public class RS {
public static String reverse(String str) {
System.out.println("--- reverse --- " + str);
if ((null == str) || (str.length() <= 1)) {
return str;
}
return add(reverse(str.substring(1)), charAt(str));
}
public static char charAt(String s) {
System.out.println("--- charAt --- " + s);
return s.charAt(0);
}
public static String add(String s, char c) {
System.out.println("--- add --- " + s + " - " + c);
return s + c;
}
public static void main(String[] args) {
System.out.println("start");
System.out.println("result: " + reverse("hello"));
System.out.println("end");
}
}
回答by Vicky K
Best Solution what I found.
我发现的最佳解决方案。
public class Manager
{
public static void main(String[] args)
{
System.out.println("Sameer after reverse : "
+ Manager.reverse("Sameer"));
System.out.println("Single Character a after reverse : "
+ Manager.reverse("a"));
System.out.println("Null Value after reverse : "
+ Manager.reverse(null));
System.out.println("Rahul after reverse : "
+ Manager.reverse("Rahul"));
}
public static String reverse(String args)
{
if(args == null || args.length() < 1
|| args.length() == 1)
{
return args;
}
else
{
return "" +
args.charAt(args.length()-1) +
reverse(args.substring(0, args.length()-1));
}
}
}
Output:C:\Users\admin\Desktop>java Manager Sameer after reverse : reemaS Single Character a after reverse : a Null Value after reverse : null Rahul after reverse : luhaR
输出:C:\Users\admin\Desktop>java Manager Sameer after reverse : reemaS Single Character a after reverse : a Null Value after reverse : null Rahul after reverse : luhaR
回答by Venkata Buchi
public class ReverseString{
private static String reverse(String text, String reverseStr){
if(text == null || text.length() == 0){
return reverseStr;
}
return reverse(text.substring(1), text.charAt(0)+reverseStr);
}
public static void main(String [] args){
System.out.println(reverse("hello", "")); //output is "olleh"
}
}
}