gpt4 book ai didi

java - Codingbat递归到while循环?

转载 作者:行者123 更新时间:2023-12-02 04:09:46 25 4
gpt4 key购买 nike

我知道递归系列上写满了“不要使用循环”,但我还是决定用循环来练习这些。我正在研究 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com