forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtedkimdev.go
More file actions
52 lines (47 loc) · 997 Bytes
/
tedkimdev.go
File metadata and controls
52 lines (47 loc) · 997 Bytes
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
// TC: O(n)
// SC: O(t) - Where n is the length of the string and t is the total number of TrieNodes created in the Trie.
type PrefixTree struct {
children map[rune]*PrefixTree
isWord bool
}
func Constructor() PrefixTree {
return PrefixTree{
children: map[rune]*PrefixTree{},
isWord: false,
}
}
func (this *PrefixTree) Insert(word string) {
cur := this
for _, c := range word {
if _, ok := cur.children[c]; !ok {
child := Constructor()
cur.children[c] = &child
cur = cur.children[c]
} else {
cur = cur.children[c]
}
}
cur.isWord = true
}
func (this *PrefixTree) Search(word string) bool {
cur := this
for _, c := range word {
if _, ok := cur.children[c]; ok {
cur = cur.children[c]
} else {
return false
}
}
return cur.isWord
}
func (this *PrefixTree) StartsWith(prefix string) bool {
cur := this
for _, c := range prefix {
if _, ok := cur.children[c]; ok {
cur = cur.children[c]
} else {
return false
}
}
return cur != nil
}