-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrie.go
60 lines (51 loc) · 1.12 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
package trie
type Node struct {
children map[rune]*Node
values []string
}
type Trie struct {
root *Node
}
func NewNode() *Node {
return &Node{children: make(map[rune]*Node)}
}
func NewTrie() *Trie {
return &Trie{root: NewNode()}
}
func (t *Trie) Insert(key string, value string) {
if key == "" {
return
}
currentNode := t.root
for _, char := range key {
if _, ok := currentNode.children[char]; !ok {
currentNode.children[char] = &Node{
children: make(map[rune]*Node),
}
}
currentNode = currentNode.children[char]
currentNode.values = append(currentNode.values, value)
}
}
func (t *Trie) Lookup(prefix string) []string {
currentNode := t.root
for _, char := range prefix {
if currentNode.children[char] == nil {
return []string{} // not found
}
currentNode = currentNode.children[char]
}
return currentNode.values
}
func (t *Trie) LookupUnique(prefix string) []string {
lookedUpValues := t.Lookup(prefix)
existing := make(map[string]bool)
var result []string
for _, v := range lookedUpValues {
if !existing[v] {
existing[v] = true
result = append(result, v)
}
}
return result
}