-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrie.go
155 lines (125 loc) · 2.25 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
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
package trie
type Trie struct {
endKey bool
tree []*Trie
cs CharSet
}
type CharSet interface {
Size() int
Position(byte) int
}
type hexCharSet struct{}
func (h *hexCharSet) Size() int {
return 16
}
func (h *hexCharSet) Position(r byte) int {
if r >= '0' && r <= '9' { // is a number
return int(r - '0')
}
if r >= 'a' && r <= 'f' { // is a letter (a-f)
return int(r-'a') + 10
}
return -1
}
type decimalCharSet struct{}
func (*decimalCharSet) Size() int {
return 10
}
func (*decimalCharSet) Position(r byte) int {
if r >= '0' && r <= '9' { // is a number
return int(r - '0')
}
return -1
}
type alfaCharSet struct{}
func (*alfaCharSet) Size() int {
return 26
}
func (*alfaCharSet) Position(r byte) int {
if r >= 'a' && r <= 'z' { // is lower case
return int(r - 'a')
}
if r >= 'A' && r <= 'Z' { // is upper case
return int(r - 'A')
}
return -1
}
var (
HexadecimalCharSet = &hexCharSet{}
DecimalCharSet = &decimalCharSet{}
EnglishAlfaCharSet = &alfaCharSet{}
)
func NewTrie(cs CharSet) *Trie {
return &Trie{
tree: make([]*Trie, cs.Size()),
cs: cs,
}
}
func (t *Trie) Add(str string) bool {
l := len(str)
if l == 0 {
return false
}
for ; l > 0; l = len(str) {
pos := t.cs.Position(str[0])
if pos < 0 || pos > t.cs.Size() {
// panic(pos)
return false
}
if t.tree[pos] == nil {
t.tree[pos] = NewTrie(t.cs)
}
if len(str) == 1 {
t.tree[pos].endKey = true
break
}
str = str[1:]
t = t.tree[pos]
}
return true
}
func (t *Trie) Find(str string) bool {
l := len(str)
if l == 0 {
return false
}
for ; l > 0; l = len(str) {
pos := t.cs.Position(str[0])
if pos < 0 || pos > len(t.tree) {
// panic("incorrect position")
return false
}
if t.tree[pos] == nil {
return false
}
if l == 1 {
return t.tree[pos].endKey
}
str = str[1:]
t = t.tree[pos]
}
return false
}
func (t *Trie) Delete(str string) bool {
l := len(str)
if l == 0 {
return false
}
for ; l > 0; l = len(str) {
pos := t.cs.Position(str[0])
if pos < 0 || pos > len(t.tree) {
// panic("incorrect position")
return false
}
if t.tree[pos] == nil {
return false
}
if l == 1 {
t.tree[pos].endKey = false
return true
}
str = str[1:]
t = t.tree[pos]
}
return false
}