繁体   English   中英

返回查询作为src的子字符串出现的次数

[英]Return the number of times query occurs as a substring of 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类之外使用方法。

错是您将err与:

i | sub
--|------
0 | ch
1 | he
2 | er
3 | rr

请注意,您要比较的这些字符串看起来很短,甚至在停止检查匹配项之前都没有到达“樱桃”的结尾。 因此,您需要在代码中修复两件事:计算end的方式以及endsrc.length()之间的比较。

提示: substring的第二个参数(结束索引)是Exclusive的

伪代码:

init 'count' and 'start' to 0
while true do
  find first occurence of 'query' in 'source', start search at 'start'
  if found
    set 'start' to found position + 1
    set count to count + 1
  else
    break out of while loop
end while
return count

提示:在source查找query时使用String#indexOf(String str, int fromIndex)

检查srcquery的存在并循环,直到返回false。 每次出现时,请使用substring ,更新count并重复直到在src中找不到query为止。

伪代码:

int count = 0;
loop (flag is true) 
  int index = find start index of query in src;
  if (query is found) 
    src = update the src with substring(index + query.length());
    count++;
  else 
    flag = false;      
return count;

这可以做到:

public static int numOccurrences(String src, String query) {
    int count = 0;
    for(int i = src.indexOf(query); i > -1;i = src.indexOf(query, i + 1)) 
        count++;
    return count;
}

在这里, isrcquery的索引,但是增量项使用indexOf(String str, int fromIndex) ,javadoc说:

从指定的索引开始,返回指定子字符串首次出现在该字符串内的索引。

将其传递给索引i1以在上次命中之后开始搜索另一个事件。

这也解决了注释中提示的NFR

相反,请查看是否可以使用String类的某些方法从一次查询跳转到下一次查询。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM