【问题标题】:How does this recursive function breaks and returns [duplicate]这个递归函数如何中断并返回[重复]
【发布时间】:2021-07-25 17:48:27
【问题描述】:

我是编码新手,对这个反向函数如何返回字符串感到困惑。我以为这将是一个无限循环。我知道当isEmpty()true 时它会中断,但为什么sentence.isEmpty() 会是true

public class Main {

  public static void main(String[] args) {
    String sentence = "Papa Jhon";
    String reversed = reverse(sentence);
    System.out.println("The reversed sentence is: " + reversed);
  }

  public static String reverse(String sentence) {
    if (sentence.isEmpty())
      return sentence;

    return reverse(sentence.substring(1)) + sentence.charAt(0);
  }
}

【问题讨论】:

  • reverse(sentence.substring(1)) 每次都会使字符串变短。最终它变成了空的。
  • sentence.substring(1) 返回一个从索引1 开始直到字符串结尾的子字符串,对于"Papa Jhon",这将产生"apa Jhon",然后作为新的@ 再次传递给函数987654331@参数。这一直持续到sentence="n",其中sentence.substring(1) 将返回空字符串""
  • “我认为这将是一个无限循环” - 你可能在这里有一个误解。您想解释一下为什么得出这个结论,即为什么您认为isEmpty() 永远不会返回true?这样我们可以帮助消除误解:)

标签: java loops recursion


【解决方案1】:

substring() 返回一个字符串,它是该字符串的子字符串。子字符串以指定索引处的字符开始并延伸到该字符串的末尾。

isEmpty() 当且仅当 length() 为 0 时返回 true。

String.substring(1) 的调用将返回一个长度为String.length()-1String,最终将返回的String 的长度减小到零。这反过来又会触发String.isEmpty()

【讨论】:

    猜你喜欢
    • 2012-04-24
    • 2016-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-03
    • 2012-02-23
    • 2020-08-24
    相关资源
    最近更新 更多