[英]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.