-
Notifications
You must be signed in to change notification settings - Fork 11
/
trie.go
94 lines (81 loc) · 1.36 KB
/
trie.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package dfa
type Node struct {
IsEnd bool
Value string
Child map[rune]*Node
}
func newNode(val string) *Node {
return &Node{
IsEnd: false,
Value: val,
Child: make(map[rune]*Node),
}
}
type Trie struct {
root *Node
size int
}
func (t *Trie) Root() *Node {
return t.root
}
func (t *Trie) Insert(key string) {
curNode := t.root
for _, v := range key {
if curNode.Child[v] == nil {
curNode.Child[v] = newNode(string(v))
}
curNode = curNode.Child[v]
curNode.Value = string(v)
}
if !curNode.IsEnd {
t.size++
curNode.IsEnd = true
}
}
func (t *Trie) PrefixMatch(key string) []string {
node, _ := t.findNode(key)
if node == nil {
return nil
}
return t.Walk(node)
}
func (t *Trie) Walk(node *Node) (ret []string) {
if node.IsEnd {
ret = append(ret, node.Value)
}
for _, v := range node.Child {
ret = append(ret, t.Walk(v)...)
}
return
}
func (t *Trie) findNode(key string) (node *Node, index int) {
curNode := t.root
f := false
for k, v := range key {
if f {
index = k
f = false
}
if curNode.Child[v] == nil {
return nil, index
}
curNode = curNode.Child[v]
if curNode.IsEnd {
f = true
}
}
if curNode.IsEnd {
index = len(key)
}
return curNode, index
}
func (t *Trie) Child(key string) *Node {
node, _ := t.findNode(key)
return node
}
func NewTrie() *Trie {
return &Trie{
root: newNode(""),
size: 0,
}
}