簡體   English   中英

是否有一種有效的方法來檢測字符串是否包含一大組特征字符串中的 substring?

[英]Is there an efficient way to detect if a string contains a substring which is in a large set of characteristic strings?

例如,給定一個字符串aaaaaaaaaXyz ,我想知道它是否包含一個 substring ,它位於特征字符串集中{'xy','xyz','zzz','cccc','dddd',....} ,它可能有 100 萬個成員。 有沒有有效的方法?

鑒於您的搜索集可能非常大,我建議只迭代該集並檢查潛在的 substring 匹配:

public boolean containsSubstring(String input, Set<String> subs) {
    boolean match = false;

    for (String sub : subs) {
        if (input.contains(sub)) {
            match = true;
            break;
        }
    }

    return match;
}

首先,你准備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);

output:

{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;
}

Clashsoft的提示下,我找到了 Aho-Corasick 算法的 java 實現,這是我想要的,感謝 Clashsoft

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM