如何在C#中创建特里

如何在C#中创建特里,第1张

如何在C#中创建特里

这是我自己的代码,从我对如何从字符数组中查找单词的答案中提取出来的?:

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;      }    }  }


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5440798.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存