public void Add(string word) { LRUPrefixTreeNode current = _root; foreach (var c in word.ToLower()) { if (!current.ContainsKey(c)) { current.Add(c, new LRUPrefixTreeNode(current, c)); } current = current[c]; } current.IsWord = true; AddToMap(current); }
private void RemoveWordFromTree(LRUPrefixTreeNode node) { node.IsWord = false; while (node.Parent != null) { if (node.Count == 0) { node.Parent.Remove(node.Value); } else { return; } node = node.Parent; } }
public bool IsWord(string word) { LRUPrefixTreeNode current = _root; foreach (var c in word.ToLower()) { if (!current.ContainsKey(c)) { return(false); } current = current[c]; } if (current.IsWord) { MoveToFront(_map[current]); } return(current.IsWord); }
public IEnumerable <string> Predict(string word) { List <string> words = new List <string>(); LRUPrefixTreeNode current = _root; foreach (var c in word.ToLower()) { if (!current.ContainsKey(c)) { return(words); } current = current[c]; } ExpandWordsFromNode(current, word.ToLower()); return(words); void ExpandWordsFromNode(LRUPrefixTreeNode node, string prefix) { if (node.IsWord) { words.Add(prefix); MoveToFront(_map[node]); } if (node.Count == 0) { return; } foreach (var subC in node.Keys) { ExpandWordsFromNode(node[subC], prefix + subC); } } }
private void AddToMap(LRUPrefixTreeNode node) { if (_map.ContainsKey(node)) { MoveToFront(_map[node]); } else { var mapNode = new LRUPrefixTreeMapNode(node); if (_tail != null) { RemoveLRU(); } else { _tail = mapNode; } MoveToFront(mapNode); _map.Add(node, mapNode); } }
internal LRUPrefixTreeMapNode(LRUPrefixTreeNode value) { Value = value; }
public LRUPrefixTree(int capacity) { _capacity = capacity; _map = new Dictionary <LRUPrefixTreeNode, LRUPrefixTreeMapNode>(capacity); _root = new LRUPrefixTreeNode(null); }