public class TrieNode {
// Initialize your data structure here.
public TrieNode() {
children = new List<TrieNode>();
hasWord = false;
}
public TrieNode(char v){
val = v;
children = new List<TrieNode>();
hasWord = false;
}
public IList<TrieNode> children;
public char val;
public bool hasWord ;
}
public class Trie {
public TrieNode root;
public Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
public void Insert(String word) {
if(string.IsNullOrEmpty(word)){
return;
}
var n = root;
var index = 0;
// try find
while(n.children.Count > 0 && index < word.Length){
var first = n.children.FirstOrDefault(x=>x.val == word[index]);
if(first != null){
n = first;
index++;
}
else{
break;
}
}
if(index < word.Length){
// if not exist , create new node
for(var i = index; i < word.Length; i++){
var child = new TrieNode(word[i]);
n.children.Add(child);
n = child;
}
}
n.hasWord = true;
}
// Returns if the word is in the trie.
public bool Search(string word) {
TrieNode n = null;
var index = TryFindNode(word, out n);
return index == word.Length && n.hasWord;
}
// Returns if there is any word in the trie
// that starts with the given prefix.
public bool StartsWith(string word) {
TrieNode n = null;
var index = TryFindNode(word, out n);
return index == word.Length;
}
private int TryFindNode(string word, out TrieNode node){
var n = root;
var index = 0;
while(n.children.Count > 0 && index < word.Length){
var first = n.children.FirstOrDefault(x => x.val == word[index]);
if(first != null){
n = first;
index++;
}
else{
break;
}
}
node = n;;
return index;
}
}版权声明:本文为博主原创文章,未经博主允许不得转载。
LeetCode -- Implement Trie (Prefix Tree)
原文:http://blog.csdn.net/lan_liang/article/details/48897013