以下是我用来在单个给定字符串中查找所有子字符串出现次数的代码。
假设完整字符串可能是作为一个字符串读取的整个文件。上述方法是否是高效的搜索方式,或者有更好或更快的方法可以实现呢?
谢谢。
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
数据结构来降低时间复杂度。 - Ashishkumar Singh{"one","onerous"}
。这几乎排除了使用带有交替项的正则表达式的可能性。 - Stephen C