例如,给定一个字符串aaaaaaaaaXyz
,我想找出它是否包含特征字符串集{'xy','xyz','zzz','cccc','dddd',....}
中的子字符串,该子字符串可能具有一百万个成员。有没有有效的方法?
答案 0 :(得分:2)
首先,您准备dictionary
。就是这样
Set<String> stringSet = Set.of("xy", "xyz", "zzz", "zzy", "cccc", "dddd");
Map<Character, List<String>> dictionary = new HashMap<>();
for (String word : stringSet)
dictionary.computeIfAbsent(word.charAt(0), k -> new ArrayList<>()).add(word);
System.out.println(dictionary);
输出:
{c=[cccc], d=[dddd], x=[xyz, xy], z=[zzy, zzz]}
您可以使用此方法进行查找。
static boolean contains(String input, Map<Character, List<String>> dictionary) {
for (int i = 0, max = input.length(); i < max; ++i) {
char first = input.charAt(i);
if (dictionary.containsKey(first))
for (String word : dictionary.get(first))
if (input.startsWith(word, i))
return true;
}
return false;
}
答案 1 :(得分:1)
鉴于您的搜索集可能非常大,我建议您仅对该集进行迭代并检查潜在的子字符串匹配项:
public boolean containsSubstring(String input, Set<String> subs) {
boolean match = false;
for (String sub : subs) {
if (input.contains(sub)) {
match = true;
break;
}
}
return match;
}
答案 2 :(得分:0)
在Clashsoft的提示下,我发现了the java implementation的Aho-Corasick算法,这是我想要的,感谢Clashsoft