【发布时间】:2010-10-20 13:06:19
【问题描述】:
为什么以下算法对我没有停止? (str 是我要搜索的字符串,findStr 是我要查找的字符串)
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;
while (lastIndex != -1) {
lastIndex = str.indexOf(findStr,lastIndex);
if( lastIndex != -1)
count++;
lastIndex += findStr.length();
}
System.out.println(count);
【问题讨论】:
-
我们在 Udacity 中做得非常好:我们使用了 newSTR = str.replace(findStr, "");并返回 count = ((str.length() - newSTR.length())/findStr.length());
-
难道你不想考虑搜索字符串的前缀是它的后缀的情况吗?在那种情况下,我认为任何建议的答案都不起作用。 here 就是一个例子。在这种情况下,您将需要更精细的算法,例如 CLRS 书中编码的 Knuth Morris Pratt(KMP)
-
它不会为您停止,因为在达到“停止”条件(lastIndex == -1)后,您通过增加 lastIndex 的值来重置它(lastIndex += findStr.length();)
-
@Sid 如果你想要这种行为,你可以每次只将 lastIndex 增加 1 而不是 findStr.length。以我为例,我只需要知道一个字符是否匹配,不介意计算多个重叠。所以只取决于每个单独的用例