java - 将递归函数转换为 for 循环?

标签 java loops recursion for-loop nested-loops

是否每个递归函数都有一个等价的 for 循环? (两者都达到相同的结果)。

我有这个递归函数:

private static boolean recur(String word, int length) {
    if(length == 1 || length == 2)
        return false;
    if(length == 0)
        return true;
    if(words[length].contains(word.substring(0, length)))
        return recur(word.substring(length), word.length() - length);
    return recur(word, length-1);
}

假设 words 是一个 Set[],其中 words[i] = 一个长度为 i 的单词集。

我想做的是: 用一个词(比如“stackoverflow”,没有空格)启动递归,我试图找出这个词是否可以被切割成子词(“stack”,“over”,“flow”)..子词的最小长度为3,假设长度为i的子词在集合words[i]中。

我可以确认这段代码有效,但它可能有内存问题,所以我想将它变成一个循环......如果可能的话。

您需要更多信息吗??

谢谢。

最佳答案

尾递归总是可以展开成一个循环,并且您的代码非常接近尾递归,所以是的。

private static boolean recur(String word, int length) {
    if(length == 1 || length == 2)
        return false;
    if(length == 0)
        return true;
    int nextLength;
    String nextWord;
    if(words[length].contains(word.substring(0, length))) {
      nextWord = word.substring(length);
      nextLength = word.length() - length;
    } else {
      nextWord = word;
      nextLength = length - 1;
    }
    return recur(nextWord, nextLength);
}

现在这是正确的尾递归。现在把它变成一个循环:

private static boolean recur(String word, int length) {
    int nextLength = length;
    String nextWord = word;
    while( true ) {
        if(nextLength == 1 || nextLength == 2)
            return false;
        if(nextLength == 0)
            return true;
        if(words[nextLength].contains(nextWord.substring(0, nextLength))) {
            nextWord = nextWord.substring(nextLength);
            nextLength = nextWord.length() - nextLength;
        } else {
            nextWord = nextWord;
            nextLength = nextLength - 1;
        }
    }
}

请注意,这段代码可以进一步优化,我只是想演示将递归变成循环的“自动”方法。

关于java - 将递归函数转换为 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4956336/

相关文章:

linux - 递归应用fold命令linux修改目录中的所有文件

c++ - 主要跳过功能?

java - 长数删除第一位 - Fast Way JAVA

java - 多语言集成测试框架

java - DefaultHttpClient 取消与服务器的连接

arrays - 向量化涉及循环中的 while 循环或 if 子句的函数 (Matlab)

java - 在 JUnit 中测试 REQUIRES_NEW

javascript - 看起来很奇怪的 Javascript for 循环

javascript - 如何在文件输入更改事件中使用循环

Python:获取对象的str时的最大递归深度