我有一个Trie数据结构,它眨眼之间搜索100 000个元素。但是,它只搜索以搜索字符串开头的单词,例如“Fi”会找到“Final”,但不会找到“GooFi”,我希望它也返回“GooFi”。这就是为什么我在这里问你们这是否是这种情况下的正确结构。我自己实现它,编写单元测试,所以它的工作到目前为止。我需要的是暗示我的目标如何实现,我不希望任何人为我编写代码,这不是我为什么在这里。无论如何这里是我的搜索实施:包含的有效搜索
public List<string> Seach(string word)
{
List<string> results = new List<string>();
this.DoSearch(this.Root, 0, new StringBuilder(word), results);
return results;
}
private void DoSearch(TrieNode currentNode, int currentPositionInWord, StringBuilder word, List<string> results)
{
if (currentPositionInWord >= word.Length)
{
this.DfsForAllWords(currentNode, word, results);
return;
}
char currentChar = word[currentPositionInWord];
bool containsKey = currentNode.Children.ContainsKey(currentChar);
if (containsKey)
{
if (currentPositionInWord == word.Length - 1)
{
results.Add(word.ToString());
}
TrieNode child = currentNode.Children[currentChar];
this.DoSearch(child, ++currentPositionInWord, word, results);
}
}
private void DfsForAllWords(TrieNode currentNode, StringBuilder word, List<string> results)
{
foreach (var node in currentNode.Children.ToArray())
{
word.Append(node.Value.Value);
if (node.Value.IsWord)
{
results.Add(word.ToString());
}
this.DfsForAllWords(node.Value, word, results);
word.Length--;
}
}
任何帮助,非常感谢。
怎么样 - http://stackoverflow.com/questions/7600292/high-performance-contains-search-in-list-of-strings-in-c-sharp?rq=1 – Vadim
为了搜索一个子串a由于您必须检查所有字符串,因此trie不会对普通列表或数组产生任何好处。对于一些想法:http://stackoverflow.com/questions/1299168/fast-filtering-of-a-string-collection-by-substring/1299211#1299211 – Guffa
那么后缀树呢? –