<分区>
有谁知道我在哪里可以找到如何在 C# 中构建 trie 的示例?我正在尝试使用字典/单词列表并用它创建一个 trie。
<分区>
有谁知道我在哪里可以找到如何在 C# 中构建 trie 的示例?我正在尝试使用字典/单词列表并用它创建一个 trie。
最佳答案
这是我自己的代码,摘 self 对 How to find a word from arrays of characters? 的回答:
public class Trie
{
public struct Letter
{
public const string Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static implicit operator Letter(char c)
{
return new Letter() { Index = Chars.IndexOf(c) };
}
public int Index;
public char ToChar()
{
return Chars[Index];
}
public override string ToString()
{
return Chars[Index].ToString();
}
}
public class Node
{
public string Word;
public bool IsTerminal { get { return Word != null; } }
public Dictionary<Letter, Node> Edges = new Dictionary<Letter, Node>();
}
public Node Root = new Node();
public Trie(string[] words)
{
for (int w = 0; w < words.Length; w++)
{
var word = words[w];
var node = Root;
for (int len = 1; len <= word.Length; len++)
{
var letter = word[len - 1];
Node next;
if (!node.Edges.TryGetValue(letter, out next))
{
next = new Node();
if (len == word.Length)
{
next.Word = word;
}
node.Edges.Add(letter, next);
}
node = next;
}
}
}
关于c# - 如何在 C# 中创建一个特里树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6416050/