-
Notifications
You must be signed in to change notification settings - Fork 0
/
Trie.cs
78 lines (68 loc) · 1.92 KB
/
Trie.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
namespace PrefixTree
{
public class Trie
{
public TrieNode RootNode
{
get;
private set;
}
public Trie()
{
RootNode = new TrieNode
{
Letter = TrieNode.Root
};
}
public void Add(string word)
{
word = word.ToLower() + TrieNode.endWord;
var currentNode = RootNode;
foreach (var letter in word)
{
currentNode = currentNode.AddChild(letter);
}
}
public List<string> Find(string prefix, int? maxMatches)
{
prefix = prefix.ToLower();
var set = new HashSet<string>();
FindRecursive(RootNode, set, "", prefix, maxMatches);
return set.ToList();
}
private static void FindRecursive(TrieNode node, ISet<string> results, string letters, string prefix, int? maxResults)
{
if (maxResults != null && results.Count == maxResults)
{
return;
}
if (node == null)
{
if (!results.Contains(letters))
{
results.Add(letters);
return;
}
}
letters += node.Letter.ToString();
if (prefix.Length > 0)
{
if (node.ContainsKey(prefix[0]))
{
FindRecursive(node[prefix[0]], results, letters, prefix.Remove(0, 1), maxResults);
}
}
else
{
foreach (char key in node.Keys)
{
FindRecursive(node[key], results, letters, prefix, maxResults);
}
}
}
}
}