-
Notifications
You must be signed in to change notification settings - Fork 0
/
mafsa.go
83 lines (64 loc) · 1.03 KB
/
mafsa.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
package mafsa
type node struct {
first, last *node // linked list of children
next *node
isWord bool
b byte
}
type builder struct {
root *node
}
func (b *builder) InsertWord(s string) {
if b.root == nil {
b.root = &node{}
}
current := b.root
i := 0
for ; i < len(s); i++ {
b := s[i]
if current.first == nil {
break
}
if current.last.b < b {
break
}
current = current.last
}
if i == len(s) {
current.isWord = true
return
}
for ; i < len(s); i++ {
n := &node{b: s[i]}
if current.last == nil {
current.first = n
current.last = n
current = n
} else {
tmp := current.last
current.last = n
tmp.next = n
current = n
}
}
current.isWord = true
}
func (b *builder) Contains(s string) bool {
if b.root == nil {
return false
}
current := b.root
Outer:
for len(s) > 0 {
b := s[0]
s = s[1:]
for cand := current.first; cand != nil; cand = cand.next {
if cand.b == b {
current = cand
continue Outer
}
}
return false
}
return current.isWord
}