-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.go
67 lines (60 loc) · 1.13 KB
/
Solution.go
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
type Trie struct {
children [26]*Trie
v int
pv int
}
func Constructor() (_ Trie) { return }
func (this *Trie) Insert(word string) {
node := this
for _, c := range word {
c -= 'a'
if node.children[c] == nil {
node.children[c] = &Trie{}
}
node = node.children[c]
node.pv++
}
node.v++
}
func (this *Trie) CountWordsEqualTo(word string) int {
node := this.search(word)
if node == nil {
return 0
}
return node.v
}
func (this *Trie) CountWordsStartingWith(prefix string) int {
node := this.search(prefix)
if node == nil {
return 0
}
return node.pv
}
func (this *Trie) Erase(word string) {
node := this
for _, c := range word {
c -= 'a'
node = node.children[c]
node.pv--
}
node.v--
}
func (this *Trie) search(word string) *Trie {
node := this
for _, c := range word {
c -= 'a'
if node.children[c] == nil {
return nil
}
node = node.children[c]
}
return node
}
/**
* Your Trie object will be instantiated and called as such:
* obj := Constructor();
* obj.Insert(word);
* param_2 := obj.CountWordsEqualTo(word);
* param_3 := obj.CountWordsStartingWith(prefix);
* obj.Erase(word);
*/