-
Notifications
You must be signed in to change notification settings - Fork 1
/
implement-trie-prefix-tree.go
72 lines (56 loc) · 1.02 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
68
69
70
71
72
package trie
type dict map[string]*Trie
type Trie struct {
node *dict
isEnd bool
}
func Constructor() Trie {
node := Trie{
node: &dict{},
}
return node
}
func (t *Trie) Insert(word string) {
cur := t.node
wordLen := len(word)
for i, v := range word {
if (*cur)[string(v)] == nil {
t := Constructor()
(*cur)[string(v)] = &t
}
if wordLen-1 == i {
(*cur)[string(v)].isEnd = true
}
cur = (*cur)[string(v)].node
}
}
func (t *Trie) Search(word string) bool {
root := t.node
wordLen := len(word)
for i, v := range word {
curNode := (*root)[string(v)]
if curNode != nil && wordLen-1 == i && curNode.isEnd {
return true
}
if curNode == nil {
return false
}
root = curNode.node
}
return false
}
func (t *Trie) StartsWith(prefix string) bool {
root := t.node
wordLen := len(prefix)
for i, v := range prefix {
curNode := (*root)[string(v)]
if wordLen-1 == i && curNode != nil {
return true
}
if curNode == nil {
return false
}
root = curNode.node
}
return false
}