-
Notifications
You must be signed in to change notification settings - Fork 0
/
trie.go
70 lines (55 loc) · 1.07 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
package tickers
// Trie is the main data structure that manages tickers
type Trie interface {
Add(Ticker)
Size() int
Search(string) []Ticker
}
type trie struct {
root *node
size int
}
var _ Trie = &trie{}
// NewTrie creates a trie in form of an interface
func NewTrie() Trie {
return &trie{
root: newNode(),
}
}
func (t *trie) Add(ticker Ticker) {
if ticker.Symbol == "" {
return
}
cur := t.root
for _, key := range ticker.Symbol {
if !cur.hasChild(key) {
cur.createChild(key)
}
cur, _ = cur.getChild(key)
}
cur.addTicker(&ticker)
t.size++
}
func (t *trie) Search(input string) []Ticker {
cur := t.root
for _, key := range input {
if !cur.hasChild(key) {
return []Ticker{}
}
cur, _ = cur.getChild(key)
}
response := cur.getTickers()
queue := append([]*node{}, cur.getChildren()...)
for len(queue) > 0 {
// Pop Front
child := queue[0]
queue = queue[1:]
response = append(response, child.getTickers()...)
// Push Front
queue = append(child.getChildren(), queue...)
}
return response
}
func (t *trie) Size() int {
return t.size
}