/** Inserts a word into the trie. */ public void Insert(string word) { Dictionary <char, TireNode> child = root.children; TireNode next = null; for (int i = 0; i < word.Length; i++) { char c = word[i]; if (child.ContainsKey(c)) { next = child[c]; } else { next = new TireNode(c); child.Add(c, next); } child = next.children; if (i == word.Length - 1) { next.isWord = true; } } }
/// <summary> /// 检测关键词 /// </summary> /// <param name="word"></param> /// <returns></returns> public bool HasWord(string word) { int idx = 0; TireNode curNode = m_HeadNode; while (idx < word.Length) { char key = word.ElementAt(idx); //如果当前节点的所有子节点中没有此字直接跳出 if (!curNode.NextNodes.ContainsKey(key)) { curNode = null; break; } curNode.NextNodes.TryGetValue(key, out curNode); idx++; } return(curNode != m_HeadNode && curNode != null && curNode.IsEnd); }
private void CreateTireTree(TireNode node, string word, int index) { if (word.Length == index) return; char key = word[index]; TireNode newNode = null; if (node.NextNode.ContainsKey(key)) { newNode = node.NextNode[key]; } else { newNode = new TireNode(key); node.NextNode.Add(key, newNode); } if (word.Length - 1 == index) { newNode.Word = word; } CreateTireTree(node.NextNode[key], word, index + 1); }
/// <summary> /// 没有释放空间版的RemoveWord /// </summary> public void RemoveWord(string word) { int idx = 0; TireNode curNode = m_HeadNode; while (idx < word.Length) { char key = word.ElementAt(idx); if (!curNode.NextNodes.ContainsKey(key)) { curNode = null; break; } curNode.NextNodes.TryGetValue(key, out curNode); idx++; } if (curNode != m_HeadNode && curNode != null && curNode.IsEnd) { curNode.IsEnd = false; } }
public TireNode SearchNode(String str) { Dictionary <char, TireNode> child = root.children; TireNode next = null; for (int i = 0; i < str.Length; i++) { char c = str[i]; if (child.ContainsKey(c)) { next = child[c]; } else { return(null); } child = next.children; } return(next); }
/// <summary> /// 添加关键词 /// </summary> /// <param name="word"></param> public void AddWord(string word) { int idx = 0; //从根节点开始 TireNode curNode = m_HeadNode; while (idx < word.Length) { char key = word.ElementAt(idx); //如果当前节点不包含这个字,则把这个字作为当前节点的子节点 if (!curNode.NextNodes.ContainsKey(key)) { curNode.NextNodes.Add(key, new TireNode()); } //把这个字的节点作为当前节点 curNode.NextNodes.TryGetValue(key, out curNode); idx++; } //最后一个节点设为末尾节点 if (curNode != m_HeadNode) { curNode.IsEnd = true; } }
/** Initialize your data structure here. */ public Trie() { root = new TireNode(); }
public void Put(char c, TireNode node) => links[c - 'a'] = node;
private TireNode m_HeadNode = null; //根节点 public TireMap() { //初始化根节点 m_HeadNode = new TireNode(); m_HeadNode.IsEnd = false; }
/** Returns if the word is in the trie. */ public bool Search(string word) { TireNode s = SearchNode(word); return(s != null && s.isWord); }