简体   繁体   English

如何使用递归来反转字符串?

[英]How to use recursion to reverse a String?

    public String reverse(String word) {

    if ((word == null) || (word.length() <= 1)) {
        return word;
    }
    return reverse(word.substring(1)) + word.charAt(0);
}

I have this code that professor sent me but I don't get it. 我有教授发送给我的这段代码,但我不明白。 I know what recursion is but I'm still a newbie at Java Programming so if anybody would care to explain to me the part return reverse(word.substring(1)) + word.charAt(0); 我知道递归是什么,但是我还是Java编程的新手,所以如果有人愿意向我解释该部分,则返回reverse(word.substring(1))+ word.charAt(0);

what does the subString(1) does and the chartAt(0)? subString(1)和chartAt(0)的作用是什么?

The way the recursive part of this works is that to reverse a string, you remove the first character, reverse what's left, and then append the first character to the result. 递归部分的工作方式是,要反转字符串,请删除第一个字符,反转剩下的内容,然后将第一个字符附加到结果中。 That's what the prof's code is doing. 那就是教授的代码正在做的事情。

  • word.substring(1) returns the substring starting at index 1 and going to the end word.substring(1)返回从索引1开始到结尾的子字符串
  • word.charAt(0) returns the character at index 0 word.charAt(0)返回索引为0的字符

There's a bit more going on when the two pieces are appended using + . 当使用+附加两个部分时,还有更多事情要做。 The issue is that word.charAt(0) has a return type of char . 问题是word.charAt(0)的返回类型为char Since the left-hand part of the + is a String , the Java language rules say that the right-hand side must be converted to a String if it isn't one. 由于+的左侧部分是String ,因此Java语言规则规定 ,如果右侧不是,则必须将其转换为String So the char value is first converted to a Character and then the toString() method of the Character class is called. 因此,首先将char值转换为Character ,然后调用Character类的toString()方法。 This returns a String consisting of the single character. 这将返回一个由单个字符组成的String

It might have been more efficient code to write that line like: 编写该行可能是更有效的代码,例如:

return reverse(word.substring(1)) + word.substring(0, 1);

The two-argument version of substring returns the substring between the two indexes. substring的两个参数版本返回两个索引之间的子字符串。 That would eliminate the autoboxing and conversion to String . 这样可以消除自动装箱和转换为String麻烦

This is recursion . 这是递归 Here are documentation for subString() and charAt() . 这是subString()charAt()的文档。 Coming to how this works: 谈到这是如何工作的:

public static String reverse(String word) {

    if ((word == null) || (word.length() <= 1)) {
        return word;
    }
    return reverse(word.substring(1)) + word.charAt(0);
}

Pass1: reverse("user") : return reverse("ser")+'u'; Pass1: reverse(“ user”): return reverse("ser")+'u';

Pass2: reverse("ser")+'u' : return reverse("er")+'s'+'u'; Pass2: reverse(“ ser”)+'u': return reverse("er")+'s'+'u';

Pass3: reverse("er")+'s'+'u' : return reverse("r")+'e'+'s'+'u'; Pass3: reverse(“ er”)+'s'+'u': return reverse("r")+'e'+'s'+'u';

Pass4: reverse("r")+'e'+'s'+'u' : return 'r'+'e'+'s'+'u'; Pass4: reverse(“ r”)+'e'+'s'+'u': return 'r'+'e'+'s'+'u'; // because here "r".length()==1 //因为这里是"r".length()==1

return reverse(word.substring(1)) + word.charAt(0);

you should read it this way: 您应该这样阅读:

  • remove the first letter away from the word word删除第一个字母
  • reverse the rest (recursive call) 撤消其余部分(递归调用)
  • put the first letter at the end 将第一个字母放在末尾

if you assume this function reverses the strings of length N, you can easily see that it must reverse the strings of length N+1. 如果假定此函数反转长度为N的字符串,则可以很容易地看出它必须反转长度为N + 1的字符串。 If you realize that the word with at most one letter is the same if reversed (the first three lines of code), you have a complete very simple proof using Mathematical Induction that this function really reverses the string. 如果您意识到反向时最多包含一个字母的单词是相同的(代码的前三行),那么您可以使用数学归纳法非常简单地证明该函数确实可以反向字符串。

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

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