我知道递归系列上写满了“不要使用循环”,但我还是决定用循环来练习这些。我正在研究 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;
}
最佳答案
除非出于某种原因您必须重新发明轮子,否则请使用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/