【发布时间】:2021-10-29 19:30:53
【问题描述】:
下面是我查找给定单个字符串中所有子字符串出现次数的代码
public static void main(String... args) {
String fullString = "one is a good one. two is ok. three is three. four is four. five is not four";
String[] severalStringArray = { "one", "two", "three", "four" };
Map<String, Integer> countMap = countWords(fullString, severalStringArray);
}
public static Map<String, Integer> countWords(String fullString, String[] severalStringArray) {
Map<String, Integer> countMap = new HashMap<>();
for (String searchString : severalStringArray) {
if (countMap.containsKey(searchString)) {
int searchCount = countMatchesInString(fullString, searchString);
countMap.put(searchString, countMap.get(searchString) + searchCount);
} else
countMap.put(searchString, countMatchesInString(fullString, searchString));
}
return countMap;
}
private static int countMatchesInString(String fullString, String subString) {
int count = 0;
int pos = fullString.indexOf(subString);
while (pos > -1) {
count++;
pos = fullString.indexOf(subString, pos + 1);
}
return count;
}
假设完整的字符串可能是作为字符串读取的完整文件。以上是搜索的有效方式还是其他更好的方式或最快的方式?
谢谢
【问题讨论】:
-
可以找
Trie数据结构降低时间复杂度 -
对于字符串匹配,您可以使用 Knuth–Morris–Pratt 算法。
-
明确地说,你问的问题是关于counting多个字符串出现在另一个字符串中的次数。这意味着涉及正则表达式等的简单解决方案不起作用。
-
另外...注意搜索字符串重叠的情况;例如
{"one","onerous"}。这几乎排除了将正则表达式与替代项一起使用。 -
@Deepeshkumar 我们需要一个带有代码 sn-p 的示例。算法对于开发人员来说太复杂了,无法理解和实现。如果你分享一个例子,理解或理解会很棒。
标签: java