java返回查询作为src的子字符串出现的次数
/** Return the number of times query occurs as a substring of src
* (different occurrences may overlap).
* Precondition: query is not the empty string "".
* Examples: For src = "ab", query = "b", return 1.
* For src = "Luke Skywalker", query = "ke", return 2.
* For src = "abababab", query = "aba", return 3.
* For src = "aaaa", query = "aa", return 3.*/
public static int numOccurrences(String src, String query) {
/* This should be done with one loop. If at all possible, don't have
* each iteration of the loop process one character of src. Instead,
* see whether some method of class String can be used to jump from one
* occurrence of query to the next. */
int count = 0;
for (int i = 0; i < src.length(); i++) {
int end = i + query.length() - 1;
if (end < src.length()) {
String sub = src.substring(i, end);
if (query.contentEquals(sub))
++count;
}
}return count;
}
我测试了代码。如果src是“cherry”,查询是“err”,那么输出应该是1,但结果是0。代码怎么了?顺便说一句,我不能在String类之外使用方法
# 1 楼答案
检查
src
中是否存在query
并循环,直到返回false。每次出现时,取substring
,更新count
并重复,直到在src中找不到query
伪代码:
# 2 楼答案
伪代码:
提示:在
source
中查找query
时使用String#indexOf(String str, int fromIndex)
# 3 楼答案
错的是,您将
err
与以下内容进行比较:请注意,您正在比较的这些字符串看起来很短,在停止检查匹配项之前,您甚至还没有到达“cherry”的末尾。因此,您需要在代码中解决两件事:计算
end
的方式以及end
和src.length()
之间的比较提示:
substring
的第二个参数(结束索引)是独占的# 4 楼答案
这就是工作:
这里,} ,javadoc说:
i
是src
中query
的索引,但是增量项使用了^{它被传递索引
i
加上1
,以开始搜索上一次命中后的另一个事件这也解决了评论中暗示的NFR: