【发布时间】:2020-08-09 15:26:11
【问题描述】:
假设我有 t 个线程,计算字符串 S 中子字符串 T 的所有非重叠出现的最佳解决方案是什么?
这是一段正常计数的代码,但我不确定如何同时实现它。如果 t 小于子字符串的长度会怎样?
public class Substrings {
public int countOccurrences(String S, String T) {
int count = 0, offset = 0, index;
while((index = S.indexOf(T, offset)) != -1) {
offset = index + T.length();
count++;
}
return count;
}
}
【问题讨论】:
-
当您想有效地计算所有不重叠的事件时,请使用
int count = 0; Matcher m = Pattern.compile(T, Pattern.LITERAL).matcher(S); while(m.find()) count++; return count;和正则表达式Patternclass,让它花时间进行准备。实际上,这意味着在内部使用Boyer–Moore algorithm,这可能比并行处理有更大的好处。
标签: java multithreading concurrency