-
Notifications
You must be signed in to change notification settings - Fork 0
/
question62.go
58 lines (51 loc) · 833 Bytes
/
question62.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
package chapter10
type (
Trie interface {
insert(word string)
search(word string) bool
startWith(prefix string) bool
}
node struct {
isWord bool
children [26]*node
}
trie struct {
root node
}
)
func newTrie() Trie {
return &trie{}
}
func (t *trie) insert(word string) {
curr := &t.root
for _, r := range word {
i := r - 'a'
n := curr.children[i]
if n == nil {
n = &node{}
curr.children[i] = n
}
curr = n
}
curr.isWord = true
}
func (t *trie) search(word string) bool {
curr := &t.root
for _, r := range word {
curr = curr.children[r-'a']
if curr == nil {
return false
}
}
return curr.isWord
}
func (t *trie) startWith(prefix string) bool {
curr := &t.root
for _, r := range prefix {
curr = curr.children[r-'a']
if curr == nil {
return false
}
}
return true
}