forked from wufenggirl/LeetCode-in-Golang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimplement-trie-prefix-tree.go
executable file
·67 lines (56 loc) · 1.07 KB
/
implement-trie-prefix-tree.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
package problem0208
/**
* Your Trie object will be instantiated and called as such:
* obj := Constructor();
* obj.Insert(word);
* param_2 := obj.Search(word);
* param_3 := obj.StartsWith(prefix);
*/
// Trie 是便于 word 插入与查找的数据结构
type Trie struct {
val byte
sons [26]*Trie
end int
}
func Constructor() Trie {
return Trie{}
}
func (this *Trie) Insert(word string) {
node := this
size := len(word)
for i := 0; i < size; i++ {
idx := word[i] - 'a'
if node.sons[idx] == nil {
node.sons[idx] = &Trie{val: word[i]}
}
node = node.sons[idx]
}
node.end++
}
func (this *Trie) Search(word string) bool {
node := this
size := len(word)
for i := 0; i < size; i++ {
idx := word[i] - 'a'
if node.sons[idx] == nil {
return false
}
node = node.sons[idx]
}
if node.end > 0 {
return true
}
return false
}
func (this *Trie) StartsWith(prefix string) bool {
node := this
size := len(prefix)
for i := 0; i < size; i++ {
idx := prefix[i] - 'a'
if node.sons[idx] == nil {
return false
}
node = node.sons[idx]
}
return true
}