-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path105ImplementTrie.go
53 lines (48 loc) · 979 Bytes
/
105ImplementTrie.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
//https://leetcode.com/problems/implement-trie-prefix-tree/description
type Trie struct {
children [26]*Trie
isEnd bool
}
func Constructor() Trie {
return Trie{}
}
func (this *Trie) Insert(word string) {
curr := this
for _, ch := range word {
i := ch - 'a'
if curr.children[i] == nil {
curr.children[i] = &Trie{}
}
curr = curr.children[i]
}
curr.isEnd = true
}
func (this *Trie) Search(word string) bool {
curr := this
for _, ch := range word {
i := ch - 'a'
if curr.children[i] == nil {
return false
}
curr = curr.children[i]
}
return curr.isEnd
}
func (this *Trie) StartsWith(prefix string) bool {
curr := this
for _, ch := range prefix {
i := ch - 'a'
if curr.children[i] == nil {
return false
}
curr = curr.children[i]
}
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);
*/