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