-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrie.go
99 lines (84 loc) · 1.71 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
package main
// A multi-set implemented as a prefix tree (trie). Multi-sets allow
// the same key multiple times.
type Set struct {
root *setNode
count int
}
type setNode struct {
children map[byte]*setNode
count int
}
func NewSet() Set {
return Set{
root: newSetNode(),
}
}
func newSetNode() *setNode {
return &setNode{
children: make(map[byte]*setNode),
}
}
func (this *Set) Len() int {
return this.count
}
func (this *Set) Put(key string) {
node := this.root
for i := 0; i < len(key); i++ {
if _, exists := node.children[key[i]]; !exists {
node.children[key[i]] = newSetNode()
}
node = node.children[key[i]]
}
node.count++
this.count++
}
func (this *Set) Count(key string) int {
node := this.getNode(key)
if node == nil {
return 0
} else {
return node.count
}
}
func (this *Set) Has(key string) bool {
node := this.getNode(key)
if node == nil {
return false
} else {
return node.count > 0
}
}
func (this *Set) Find(prefix string, max int) []string {
node := this.getNode(prefix)
if node == nil {
return []string{}
}
return this.findRecursively(prefix, max, node, []string{})
}
func (this *Set) findRecursively(prefix string, max int, node *setNode, results []string) []string {
if node == nil {
return results
}
if node.count > 0 {
results = append(results, prefix)
}
if len(results) < max {
for ch, node := range node.children {
if node != nil {
results = this.findRecursively(prefix+string(ch), max, node, results)
}
}
}
return results
}
func (this *Set) getNode(key string) *setNode {
node := this.root
for i := 0; i < len(key); i++ {
if _, exists := node.children[key[i]]; !exists {
return nil
}
node = node.children[key[i]]
}
return node
}