-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrie.go
More file actions
85 lines (74 loc) · 1.57 KB
/
Copy pathtrie.go
File metadata and controls
85 lines (74 loc) · 1.57 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
package gohoa
const (
TEXT_TRIE = iota
NUM_TRIE
)
type Node struct {
Children []*Node
isEnd bool
}
func NewNode(tType int) *Node {
if tType == NUM_TRIE {
return &Node{Children: make([]*Node, 10)}
}
return &Node{Children: make([]*Node, 26)}
}
type Trie struct {
root *Node
trieType int
asciRune rune
}
func InitTrie(tType int) *Trie {
asciiRune := '0'
if tType == TEXT_TRIE {
asciiRune = 'a'
}
return &Trie{NewNode(tType), tType, asciiRune}
}
func (t *Trie) Insert(key string) {
node := t.root
for _, c := range key {
myIdx := c - t.asciRune
if node.Children[myIdx] == nil {
node.Children[myIdx] = NewNode(t.trieType)
}
node = node.Children[myIdx]
}
node.isEnd = true
}
func (t *Trie) Search(key string) bool {
node := t.root
for _, c := range key {
myIdx := c - t.asciRune
if node.Children[myIdx] == nil {
return false
}
node = node.Children[myIdx]
}
return node.isEnd
}
func (t *Trie) Suggestions(key string) []string {
node := t.root
for _, c := range key {
myIdx := c - t.asciRune
if node.Children[myIdx] == nil {
return nil
}
node = node.Children[myIdx]
}
return t.suggestionsFromNode(node, key)
}
func (t *Trie) suggestionsFromNode(node *Node, prefix string) []string {
var suggestions []string
if node.isEnd {
suggestions = append(suggestions, prefix)
}
for i, child := range node.Children {
if child != nil {
childPrefix := prefix + string(t.asciRune+rune(i))
childSuggestions := t.suggestionsFromNode(child, childPrefix)
suggestions = append(suggestions, childSuggestions...)
}
}
return suggestions
}