java - Codingbat递归到while循环?

标签 java recursion while-loop

我知道递归系列上写满了“不要使用循环”,但我还是决定用循环来练习这些。我正在研究 strDist() ,但我似乎无法完全理解它。

问题:

给定一个字符串和一个非空子字符串 sub,递归计算以 sub 开头和结尾的最大子字符串并返回其长度。

strDist("catcowcat", "cat") → 9
strDist("catcowcat", "cow") → 3
strDist("cccatcowcatxx", "cat") → 9

我的代码:

public int strDist(String str, String sub) {
    int min = 0;
    int max = str.length() - 1;
    int index = 0;
    if (str.isEmpty()) {
        return 0;
    }
    while (index < str.length()) {
        if (str.substring(index, index + sub.length()).equals(sub)) {
            min = index;
            index = str.length();
        }
        index++;
    }
    index = str.length() - 1;
    while (index >= 0) {
        if (str.substring(index - sub.length(), index).equals(sub)) {
            max = index;
            index = 0;
        }
        index--;
    }
    return max - min;
}

enter image description here

最佳答案

除非出于某种原因您必须重新发明轮子,否则请使用String.indexOf(String)String.lastIndexOf(String)喜欢

public static int strDist(String str, String sub) {
    if (str.contains(sub)) {
        return sub.length() + str.lastIndexOf(sub) - str.indexOf(sub);
    }
    return 0;
}

关于java - Codingbat递归到while循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33907443/

相关文章:

java - 为什么我的 Ant 删除不起作用?

java - 创建自己的 "SeekBar"

java - String.valueOf() 和 new String() 的区别

SQL 递归 CTE 链接链

haskell - 原始递归函数

c - 简单的 C 菜单构建,Scanf 不拖拉输入

c++ - 我正在计算的序列(冰雹)在需要打印一次时打印两次

java - 谷歌应用程序引擎中的 Getkey() 返回 id

list - 如果原子在列表中则返回 True 的 LISP 函数

javascript - 为什么我的 do-while 循环不起作用? (函数内生成的多个变量)