-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtrie.go
94 lines (80 loc) · 1.67 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*
FROM: https://leetcode.com/problems/implement-trie-prefix-tree/description/
*/
package trie
type trieNode struct {
Val rune
IsEnd bool
Next map[rune]*trieNode
}
type Trie struct {
root *trieNode
}
/** Initialize your data structure here. */
func Constructor() Trie {
return Trie{root: &trieNode{Next: make(map[rune]*trieNode)}}
}
/** Inserts a word into the trie. */
func (this *Trie) Insert(word string) {
if len(word) == 0 {
panic("Length of word must > 0.")
}
var (
rword = []rune(word)
curNode = this.root
tmp *trieNode
ok bool
)
for _, letter := range rword {
if tmp, ok = curNode.Next[letter]; !ok {
tmp = &trieNode{Val: letter, Next: make(map[rune]*trieNode)}
curNode.Next[letter] = tmp
}
curNode = tmp
}
curNode.IsEnd = true
}
/** Returns if the word is in the trie. */
func (this *Trie) Search(word string) bool {
if len(word) == 0 {
return false
}
var (
rword = []rune(word)
curNode = this.root
ok bool
)
for _, letter := range rword {
if curNode, ok = curNode.Next[letter]; !ok {
return false
}
}
if !curNode.IsEnd {
return false
}
return true
}
/** Returns if there is any word in the trie that starts with the given prefix. */
func (this *Trie) StartsWith(prefix string) bool {
if len(prefix) == 0 {
return false
}
var (
rword = []rune(prefix)
curNode = this.root
ok bool
)
for _, letter := range rword {
if curNode, ok = curNode.Next[letter]; !ok {
return false
}
}
return true
}
/**
* Your Trie object will be instantiated and called as such:
* obj := Constructor();
* obj.Insert(word);
* param_2 := obj.Search(word);
* param_3 := obj.StartsWith(prefix);
*/