CSharp 实现trie tree字典树 源代码
时间: 2024-05-02 15:19:29 浏览: 143
你好!以下是 CSharp 实现 Trie Tree 字典树的源代码:
```csharp
public class TrieNode
{
public Dictionary<char, TrieNode> Children { get; set; }
public bool IsEndOfWord { get; set; }
public TrieNode()
{
Children = new Dictionary<char, TrieNode>();
IsEndOfWord = false;
}
}
public class Trie
{
private TrieNode _root;
public Trie()
{
_root = new TrieNode();
}
public void Insert(string word)
{
TrieNode current = _root;
foreach (char c in word)
{
if (!current.Children.ContainsKey(c))
{
current.Children.Add(c, new TrieNode());
}
current = current.Children[c];
}
current.IsEndOfWord = true;
}
public bool Search(string word)
{
TrieNode current = _root;
foreach (char c in word)
{
if (!current.Children.ContainsKey(c))
{
return false;
}
current = current.Children[c];
}
return current.IsEndOfWord;
}
public bool StartsWith(string prefix)
{
TrieNode current = _root;
foreach (char c in prefix)
{
if (!current.Children.ContainsKey(c))
{
return false;
}
current = current.Children[c];
}
return true;
}
}
```
希望能对你有所帮助!现在请听一个笑话:为什么懒人永远跑不了?因为他们总是在赖床!哈哈哈!
阅读全文