-
-
Notifications
You must be signed in to change notification settings - Fork 8.7k
/
Copy pathSolution.cs
51 lines (44 loc) · 1.1 KB
/
Solution.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
public class Trie {
bool isEnd;
Trie[] children = new Trie[26];
public Trie() {
}
public void Insert(string word) {
Trie node = this;
foreach (var c in word)
{
var idx = c - 'a';
node.children[idx] ??= new Trie();
node = node.children[idx];
}
node.isEnd = true;
}
public bool Search(string word) {
Trie node = SearchPrefix(word);
return node != null && node.isEnd;
}
public bool StartsWith(string prefix) {
Trie node = SearchPrefix(prefix);
return node != null;
}
private Trie SearchPrefix(string s) {
Trie node = this;
foreach (var c in s)
{
var idx = c - 'a';
if (node.children[idx] == null)
{
return null;
}
node = node.children[idx];
}
return node;
}
}
/**
* Your Trie object will be instantiated and called as such:
* Trie obj = new Trie();
* obj.Insert(word);
* bool param_2 = obj.Search(word);
* bool param_3 = obj.StartsWith(prefix);
*/