forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
208-Implement-Trie.go
54 lines (44 loc) · 901 Bytes
/
208-Implement-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
type Trie struct {
children [26]*Trie
endOfWord bool
root *Trie
}
func Constructor() Trie {
return Trie{
children: [26]*Trie{},
endOfWord: false,
root: &Trie{}}
}
func (this *Trie) Insert(word string) {
cur := this.root
for i := 0; i < len(word); i++ {
index := word[i] - 'a'
if cur.children[index] == nil {
cur.children[index] = &Trie{}
}
cur = cur.children[index]
}
cur.endOfWord = true
}
func (this *Trie) Search(word string) bool {
cur := this.root
for i := 0; i < len(word); i++ {
index := word[i] - 'a'
if cur.children[index] == nil {
return false
}
cur = cur.children[index]
}
return cur.endOfWord
}
func (this *Trie) StartsWith(prefix string) bool {
cur := this.root
for i := 0; i < len(prefix); i++ {
index := prefix[i] - 'a'
if cur.children[index] == nil {
return false
}
cur = cur.children[index]
}
return true
}