簡體   English   中英

查找列表中字符串首次出現的更快方法

[英]Faster way to find first occurence of String in list

我有一個方法,可以找到單詞列表中的第一個匹配項。 wordSet我需要檢查的一組單詞該列表是文本的表示形式,因此該單詞具有順序排列的單詞。 因此,如果pwWords具有吮吸元素{This,is,good,boy,and,this,girl,is,bad} pwWords {This,is,good,boy,and,this,girl,is,bad}並且wordSet具有{this,is}方法應僅對前兩個元素添加true。 我的問題是:有沒有更快的方法可以做到這一點? 因為如果pwWords有超過一百萬個元素,而wordSet超過一萬個,則它的工作速度非常慢。

public List<bool> getFirstOccurances(List<string> pwWords)
    {
        var firstOccurance = new List<bool>();
        var wordSet = new List<String>(WordsWithFDictionary.Keys);
        foreach (var pwWord in pwWords)
        {
            if (wordSet.Contains(pwWord))
            {
                firstOccurance.Add(true);
                wordSet.Remove(pwWord);
            }
            else
            {
                firstOccurance.Add(false);
            }
        }
        return firstOccurance;
    }

另一種方法是將HashSet用於wordSet

public List<bool> getFirstOccurances(List<string> pwWords)
{
    var wordSet = new HashSet<string>(WordsWithFDictionary.Keys);
    return pwWords.Select(word => wordSet.Contains(word)).ToList();
}

HashSet.Contains算法為O(1),其中List.Contains將循環所有項目,直到找到項目。

為了獲得更好的性能,您只能在可能的情況下創建一次wordSet

public class FirstOccurances
{
    private HashSet<string> _wordSet;

    public FirstOccurances(IEnumerable<string> wordKeys)
    {
        _wordSet = new HashSet<string>(wordKeys);
    }

    public List<bool> GetFor(List<string> words)
    {
        return words.Select(word => _wordSet.Contains(word)).ToList();
    }
}

然后用

var occurrences = new FirstOccurances(WordsWithFDictionary.Keys);

// Now you can effectively search for occurrences multiple times
var result = occurrences.GetFor(pwWords);
var anotherResult = occurrences.GetFor(anotherPwWords);

因為可以獨立檢查pwWords項目是否出現,並且如果未導入項目的順序,則可以嘗試使用Parallel LINQ

public List<bool> GetFor(List<string> words)
{
    return words.AsParallel().Select(word => _wordSet.Contains(word)).ToList();
}

暫無
暫無

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

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