-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtrie.go
More file actions
131 lines (116 loc) · 2.15 KB
/
trie.go
File metadata and controls
131 lines (116 loc) · 2.15 KB
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package aho_corasick
/*
@Author: orbit-w
@File: trie
@2023 10月 周二 18:56
*/
type Node struct {
isRoot bool
isLeaf bool
code rune
depth int
index int
father *Node
fail *Node
children []*Node
output []rune
}
func (ins *Node) findChild(r rune) *Node {
for _, child := range ins.children {
if child.code == r {
return child
}
}
return nil
}
func (ins *Node) Root() bool {
return ins.isRoot
}
func (ins *Node) Exist() bool {
return len(ins.output) > 0
}
func (ins *Node) Code() int {
return int(ins.code)
}
type Trie struct {
count int32
root *Node
}
func (ins *Trie) Build(ks StrKeySlice) {
ins.root = &Node{
isRoot: true,
depth: 0,
index: IndexRoot,
}
for _, key := range ks {
father := ins.root
for i, r := range key {
child := father.findChild(r)
if child == nil {
child = &Node{
code: r,
isLeaf: i == len(key)-1,
depth: father.depth + 1,
father: father,
}
if child.isLeaf {
child.output = append(child.output, rune(len(key)))
}
ins.count++
father.children = append(father.children, child)
}
father = child
}
}
}
func (ins *Trie) f(node *Node) {
fail := ins.g(node)
if len(fail.output) > 0 {
node.output = append(node.output, fail.output...)
}
node.fail = fail
}
func (ins *Trie) g(node *Node) (fail *Node) {
for fn := node.father.fail; fn != nil; fn = fn.fail {
if fail = fn.findChild(node.code); fail != nil {
return
}
}
fail = ins.root
return
}
func (ins *Trie) BFS(iter func(node *Node) bool) {
queue := make([]*Node, 0, ins.count+1)
queue = append(queue, ins.root)
for len(queue) > 0 {
//pop
head := queue[0]
queue = queue[1:]
stop := iter(head)
if stop {
break
}
for i := range head.children {
child := head.children[i]
queue = append(queue, child)
}
}
}
func (ins *Trie) DFS(iter func(node *Node) bool) {
stack := NodeStack{}
stack.Push(ins.root)
for stack.Length() > 0 {
head := stack.Pop()
stop := iter(head)
if stop {
break
}
for i := len(head.children) - 1; i >= 0; i-- {
child := head.children[i]
stack.Push(child)
}
}
}
func (ins *Trie) Free() {
ins.root = nil
}