-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrie.go
66 lines (56 loc) · 1 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
package main
import "fmt"
type Node struct {
Value string
Next map[rune]*Node
}
func NewNode() *Node {
return &Node{
Value: "",
Next: make(map[rune]*Node),
}
}
func (root *Node) Put(key string, value string) error {
current := root
for _, r := range key {
next, ok := current.Next[r]
if !ok {
next = NewNode()
current.Next[r] = next
}
current = next
}
current.Value = value
return nil
}
func (root *Node) Get(key string) (string, bool) {
current := root
for _, r := range key {
next, ok := current.Next[r]
if !ok {
return "", false
}
current = next
}
if current.Value != "" {
return current.Value, true
}
return "", false
}
func (root *Node) Delete(key string) error {
current := root
var prev *Node
for _, r := range key {
prev = current
next, ok := current.Next[r]
if !ok {
return fmt.Errorf(key + " not found")
}
current = next
}
current.Value = ""
if len(current.Next) == 0 && prev != nil {
delete(prev.Next, []rune(key)[0])
}
return nil
}