-
Notifications
You must be signed in to change notification settings - Fork 0
/
searchtree.go
70 lines (62 loc) · 1.1 KB
/
searchtree.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
package trygo
import (
"fmt"
)
type SearchTreeNode struct {
Chars []rune
Children []*SearchTreeNode
End bool
}
func NewSearchTree() *SearchTreeNode {
return new(SearchTreeNode)
}
func (n *SearchTreeNode) hasChar(c rune) (bool, int) {
for idx, cc := range n.Chars {
if c == cc {
return true, idx
}
}
return false, -1
}
func (n *SearchTreeNode) addChar(c rune) *SearchTreeNode {
n.Chars = append(n.Chars, c)
nn := new(SearchTreeNode)
n.Children = append(n.Children, nn)
return nn
}
func (n *SearchTreeNode) Print() {
fmt.Print("{")
if n.End {
fmt.Print(".")
}
for idx, c := range n.Chars {
fmt.Print(string(c))
n.Children[idx].Print()
}
fmt.Print("}")
}
func (n *SearchTreeNode) Contain(word string) (ret bool) {
cur := n
for _, c := range word {
if ok, idx := cur.hasChar(c); ok {
cur = cur.Children[idx]
} else {
return
}
}
if cur.End {
ret = true
}
return
}
func (n *SearchTreeNode) Add(word string) {
cur := n
for _, c := range word {
if ok, idx := cur.hasChar(c); ok {
cur = cur.Children[idx]
} else {
cur = cur.addChar(c)
}
}
cur.End = true
}