【问题标题】:Is there an efficient way to detect if a string contains a substring which is in a large set of characteristic strings?是否有一种有效的方法来检测字符串是否包含大量特征字符串中的子字符串?
【发布时间】:2020-11-26 12:18:47
【问题描述】:

例如,给定一个字符串aaaaaaaaaXyz,我想知道它是否包含一个子字符串,该子字符串位于特征字符串集{'xy','xyz','zzz','cccc','dddd',....} 中,它可能有100 万个成员。有没有有效的方法?

【问题讨论】:

标签: java string algorithm contains


【解决方案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;
}

【讨论】:

  • 这不是一种“高效”的方式。
  • @Olivier 怎么不高效?
【解决方案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;
}

【讨论】:

    【解决方案3】:

    在Clashsoft的提示下,我找到了Aho-Corasick算法的the java implementation,这是我想要的,感谢Clashsoft

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-13
      • 2020-01-19
      • 1970-01-01
      • 2020-07-16
      • 2011-11-09
      相关资源
      最近更新 更多