-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path00208-implement_trie_prefix_tree.go
80 lines (59 loc) · 1.22 KB
/
00208-implement_trie_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
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
// 208: Implement Trie Prefix Tree
// https://leetcode.com/problems/implement-trie-prefix-tree
package main
import (
"fmt"
)
type Trie struct {
children [26]*Trie
isWord bool
}
func Constructor() Trie {
return Trie{}
}
func (this *Trie) Insert(word string) {
node := this
current := 0
for i:=0; i<len(word); i++ {
current = int(word[i] - 'a')
if node.children[current] == nil {
node.children[current] = &Trie{}
}
node = node.children[current]
}
node.isWord = true
}
func (this *Trie) Search(word string) bool {
node := this
current := 0
for i:=0; i<len(word); i++ {
current = int(word[i] - 'a')
if node.children[current] == nil {
return false
}
node = node.children[current]
}
return node.isWord
}
func (this *Trie) StartsWith(prefix string) bool {
node := this
current := 0
for i:=0; i<len(prefix); i++ {
current = int(prefix[i] - 'a')
if node.children[current] == nil {
return false
}
node = node.children[current]
}
return true
}
func main() {
trie := Constructor()
// OPERATIONS
trie.Insert("apple")
fmt.Println(trie.Search("apple"))
fmt.Println(trie.Search("app"))
fmt.Println(trie.StartsWith("app"))
trie.Insert("app")
fmt.Println(trie.Search("app"))
}