-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0208-implement-trie-prefix-tree.cs
57 lines (50 loc) · 1.34 KB
/
0208-implement-trie-prefix-tree.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
public class TrieNode {
public TrieNode() {
childrenMap = new Dictionary<char, TrieNode>();
}
public Dictionary<char, TrieNode> childrenMap { get; set; }
public bool isWord{ get; set; }
}
public class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
public void Insert(string word) {
var cur = root;
foreach(var c in word) {
if(!cur.childrenMap.ContainsKey(c)) {
cur.childrenMap[c] = new TrieNode();
}
cur = cur.childrenMap[c];
}
cur.isWord = true;
}
public bool Search(string word) {
var node = traverse(word);
return node != null && node.isWord;
}
public bool StartsWith(string prefix) {
var node = traverse(prefix);
return node!= null;
}
private TrieNode traverse(string path) {
var cur = root;
foreach(var c in path) {
if(cur.childrenMap.ContainsKey(c)){
cur = cur.childrenMap[c];
}
else {
return null;
}
}
return cur;
}
}
/**
* 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);
*/