1 Star 0 Fork 0

agony/LeetCode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
208.ImplementTrie.cs 1.48 KB
一键复制 编辑 原始数据 按行查看 历史
Kai Yang 提交于 2015-07-21 21:29 . 208. Implement Trie (Prefix Tree)
using System.Collections.Generic;
using System.Linq;
class TrieNode {
public bool IsEnd { get; set; }
public TrieNode[] Children { get; set; }
public TrieNode() {
Children = new TrieNode[26];
}
}
public class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
public void Insert(string word) {
var node = root;
for (var i = 0; i < word.Length; ++i)
{
TrieNode nextNode;
var index = word[i] - 'a';
nextNode = node.Children[index];
if (nextNode == null)
{
nextNode = new TrieNode();
node.Children[index] = nextNode;
}
node = nextNode;
}
node.IsEnd = true;
}
public bool Search(string word) {
var node = root;
for (var i = 0; i < word.Length; ++i)
{
var nextNode = node.Children[word[i] - 'a'];
if (nextNode == null)
{
return false;
}
node = nextNode;
}
return node.IsEnd;
}
public bool StartsWith(string word) {
var node = root;
for (var i = 0; i < word.Length; ++i)
{
var nextNode = node.Children[word[i] - 'a'];
if (nextNode == null)
{
return false;
}
node = nextNode;
}
return node.IsEnd || node.Children.Any(c => c != null);
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C#
1
https://gitee.com/agony2020/LeetCode.git
git@gitee.com:agony2020/LeetCode.git
agony2020
LeetCode
LeetCode
master

搜索帮助