c# - 如何在 C# 中创建一个特里树

标签 c# algorithm data-structures 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/

相关文章:

javascript - 使用随机枢轴在 Javascript 中实现 QuickSort

java - 匈牙利算法 : How to cover 0 elements with minimum lines?

algorithm - 如何自动计算轴刻度和间隔?

data-structures - 如何确保 Rust 向量仅包含交替类型?

c# - 如何从 C# 中的 LinkedList 中删除与给定条件匹配的元素?

c++ - 确定性句柄分配算法

c# - 在当前线程执行任务

c# - 我将如何进行单元测试?

c# - 使用 Powershell 自动设置 MSMQ

c# - 基本 Controller 中的属性不会在 mvc5 的单元测试中触发