-
Notifications
You must be signed in to change notification settings - Fork 0
/
prefix_tree.go
54 lines (46 loc) · 1008 Bytes
/
prefix_tree.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
package main
type TrieNode struct {
children map[string]*TrieNode
isEnd bool
}
type PrefixTree struct {
root *TrieNode
}
func NewPrefixTree() *PrefixTree {
return &PrefixTree{
root: &TrieNode{
children: make(map[string]*TrieNode),
isEnd: false,
},
}
}
func (t *PrefixTree) Insert(stringSlice []string) {
node := t.root
for _, s := range stringSlice {
if _, exists := node.children[s]; !exists {
node.children[s] = &TrieNode{
children: make(map[string]*TrieNode),
isEnd: false,
}
}
node = node.children[s]
}
node.isEnd = true
}
func (t *PrefixTree) HasPrefix(prefixSlice []string) bool {
node := t.root
for _, s := range prefixSlice {
if _, exists := node.children[s]; !exists {
return false
}
node = node.children[s]
}
return true
}
/* Sample usage:
tree := NewPrefixTree()
tree.Insert([]string{"a", "b", "c"})
tree.Insert([]string{"a", "b", "d"})
tree.Insert([]string{"a", "b", "e"})
fmt.Println(tree.FindPrefixes([]string{"a", "b"}))
*/