[英]Efficient way to find “hook words” in a list of words?
钩子词是一个单词,您可以在开头或结尾添加一个字母并创建一个新单词。
我有一个相当大的单词列表(大约170k),我想选择5个随机钩字。 问题是我使用的方法非常慢。 见下文:
Random rnd = new Random();
var hookBases = (from aw in allWords //allWords is a List<string>
from aw2 in allWords
where aw2.Contains(aw)
&& aw2.Length == aw.Length + 1
&& aw[0] == 'c'
select aw).OrderBy(t => rnd.Next()).Take(5);
当我尝试从hookBase
访问任何东西时,它会旋转几分钟然后我放弃并杀死它。
任何人都可以看到我试图这样做的任何明显错误? 有关更有效方式的任何建议吗?
首先,allWords应该是HashSet<string>
,而不是List<string>
,以便有效查找。
一旦完成,迭代哈希集,并检查删除第一个或最后一个字母是否给出了一个新的有效单词。 那是你的勾手词。
HashSet<string> result = new HashSet<string>();
foreach (string word in allWords) {
string candidate = word.Substring(0, word.Length - 1);
if (allWords.Contains(candidate)) { result.Add(candidate); }
candidate = word.Substring(1, word.Length - 1);
if (allWords.Contains(candidate)) { result.Add(candidate); }
}
如果你想用LINQ做这个:
List<string> hookWords = allWords
.Select(word => word.Substring(0, word.Length - 1))
.Concat(allWords.Select(word => word.Substring(1, word.Length - 1)))
.Distinct()
.Where(candidate => allWords.Contains(candidate))
.ToList();
看到它在线工作: ideone
我最近做了类似的事。 我尝试使用linq,在ddbb和存储过程中存储带有正则表达式的.net程序集。 我发现最有效的方法是使用存储过程。 针对此类操作,Microsoft已对该交易引擎进行了高度优化。
最好的祝福
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.