-
Notifications
You must be signed in to change notification settings - Fork 292
/
Trie.cs
273 lines (228 loc) · 7.34 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Advanced.Algorithms.DataStructures;
/// <summary>
/// A trie (prefix tree) implementation.
/// </summary>
public class Trie<T> : IEnumerable<T[]>
{
public Trie()
{
Root = new TrieNode<T>(null, default);
Count = 0;
}
private TrieNode<T> Root { get; }
public int Count { get; private set; }
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<T[]> GetEnumerator()
{
return new TrieEnumerator<T>(Root);
}
/// <summary>
/// Insert a new record to this trie.
/// Time complexity: O(m) where m is the length of entry.
/// </summary>
public void Insert(T[] entry)
{
Insert(Root, entry, 0);
Count++;
}
/// <summary>
/// Insert a new record to this trie after finding the end recursively.
/// </summary>
private void Insert(TrieNode<T> currentNode, T[] entry, int currentIndex)
{
while (true)
{
if (currentIndex == entry.Length)
{
currentNode.IsEnd = true;
return;
}
if (currentNode.Children.ContainsKey(entry[currentIndex]) == false)
{
var newNode = new TrieNode<T>(currentNode, entry[currentIndex]);
currentNode.Children.Add(entry[currentIndex], newNode);
currentNode = newNode;
currentIndex = currentIndex + 1;
}
else
{
currentNode = currentNode.Children[entry[currentIndex]];
currentIndex = currentIndex + 1;
}
}
}
/// <summary>
/// Deletes a record from this trie.
/// Time complexity: O(m) where m is the length of entry.
/// </summary>
public void Delete(T[] entry)
{
Delete(Root, entry, 0);
Count--;
}
/// <summary>
/// Deletes a record from this trie after finding it recursively.
/// </summary>
private void Delete(TrieNode<T> currentNode, T[] entry, int currentIndex)
{
if (currentIndex == entry.Length)
{
if (!currentNode.IsEnd) throw new Exception("Item not in trie.");
currentNode.IsEnd = false;
return;
}
if (currentNode.Children.ContainsKey(entry[currentIndex]) == false) throw new Exception("Item not in trie.");
Delete(currentNode.Children[entry[currentIndex]], entry, currentIndex + 1);
if (currentNode.Children[entry[currentIndex]].IsEmpty
&& !currentNode.IsEnd)
currentNode.Children.Remove(entry[currentIndex]);
}
/// <summary>
/// Returns a list of records matching this prefix.
/// Time complexity: O(rm) where r is the number of results and m is the average length of each entry.
/// </summary>
public List<T[]> StartsWith(T[] prefix)
{
return StartsWith(Root, prefix, 0);
}
/// <summary>
/// Recursively visit until end of prefix
/// and then gather all sub entries under it.
/// </summary>
private List<T[]> StartsWith(TrieNode<T> currentNode, T[] searchPrefix, int currentIndex)
{
while (true)
{
if (currentIndex == searchPrefix.Length)
{
var result = new List<T[]>();
//gather sub entries and prefix them with search entry prefix
GatherStartsWith(result, searchPrefix, new List<T>(), currentNode);
return result;
}
if (currentNode.Children.ContainsKey(searchPrefix[currentIndex]) == false) return new List<T[]>();
currentNode = currentNode.Children[searchPrefix[currentIndex]];
currentIndex = currentIndex + 1;
}
}
/// <summary>
/// Gathers all suffixes under this node appending with the given prefix.
/// </summary>
private void GatherStartsWith(List<T[]> result, T[] searchPrefix, List<T> suffix,
TrieNode<T> node)
{
//end of word
if (node.IsEnd)
{
if (suffix != null)
result.Add(searchPrefix.Concat(suffix).ToArray());
else
result.Add(searchPrefix);
}
//visit all children
foreach (var child in node.Children)
{
//append to end of prefix for new prefix
suffix.Add(child.Key);
GatherStartsWith(result, searchPrefix, suffix, child.Value);
suffix.RemoveAt(suffix.Count - 1);
}
}
/// <summary>
/// Returns true if the entry exist.
/// Time complexity: O(e) where e is the length of the given entry.
/// </summary>
public bool Contains(T[] entry)
{
return Contains(Root, entry, 0, false);
}
/// <summary>
/// Returns true if any records match this prefix.
/// Time complexity: O(e) where e is the length of the given entry.
/// </summary>
public bool ContainsPrefix(T[] prefix)
{
return Contains(Root, prefix, 0, true);
}
/// <summary>
/// Find if the record exist recursively.
/// </summary>
private bool Contains(TrieNode<T> currentNode, T[] entry, int currentIndex, bool isPrefixSearch)
{
while (true)
{
if (currentIndex == entry.Length) return isPrefixSearch || currentNode.IsEnd;
if (currentNode.Children.ContainsKey(entry[currentIndex]) == false) return false;
currentNode = currentNode.Children[entry[currentIndex]];
currentIndex = currentIndex + 1;
}
}
}
internal class TrieNode<T>
{
internal TrieNode(TrieNode<T> parent, T value)
{
Parent = parent;
Value = value;
Children = new Dictionary<T, TrieNode<T>>();
}
internal bool IsEmpty => Children.Count == 0;
internal bool IsEnd { get; set; }
internal TrieNode<T> Parent { get; set; }
internal Dictionary<T, TrieNode<T>> Children { get; set; }
internal T Value { get; set; }
}
internal class TrieEnumerator<T> : IEnumerator<T[]>
{
private readonly TrieNode<T> root;
private Stack<TrieNode<T>> progress;
internal TrieEnumerator(TrieNode<T> root)
{
this.root = root;
}
public bool MoveNext()
{
if (root == null) return false;
if (progress == null) progress = new Stack<TrieNode<T>>(root.Children.Select(x => x.Value));
while (progress.Count > 0)
{
var next = progress.Pop();
foreach (var child in next.Children) progress.Push(child.Value);
if (next.IsEnd)
{
Current = GetValue(next);
return true;
}
}
return false;
}
public void Reset()
{
progress = null;
Current = null;
}
public T[] Current { get; private set; }
object IEnumerator.Current => Current;
public void Dispose()
{
progress = null;
}
private T[] GetValue(TrieNode<T> next)
{
var result = new Stack<T>();
result.Push(next.Value);
while (next.Parent != null && !next.Parent.Value.Equals(default(T)))
{
next = next.Parent;
result.Push(next.Value);
}
return result.ToArray();
}
}