-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdesign-add-and-search-words-data-structure.go
83 lines (71 loc) · 1.52 KB
/
design-add-and-search-words-data-structure.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
package main
// source: https://leetcode.com/problems/design-add-and-search-words-data-structure/
type Trie struct {
Children map[rune]*Trie
Term bool
}
func NewTrie() *Trie {
return &Trie{Children: make(map[rune]*Trie)}
}
func (t *Trie) Insert(word string) {
for _, r := range word {
if t.Children[r] == nil {
t.Children[r] = NewTrie()
}
t = t.Children[r]
}
t.Term = true
}
func (t *Trie) Search(word string) bool {
var dfs func(p *Trie, word []rune) bool
dfs = func(p *Trie, word []rune) bool {
if len(word) == 0 {
return p.Term == true
}
if p == nil {
return false
}
r := word[0]
if r == '.' {
for rr := range p.Children {
if dfs(p.Children[rr], word[1:]) {
return true
}
}
return false
} else if p.Children[r] == nil {
return false
}
return dfs(p.Children[r], word[1:])
}
return dfs(t, []rune(word))
}
type WordDictionary struct {
data Trie
}
func Constructor() WordDictionary {
return WordDictionary{data: *NewTrie()}
}
func (this *WordDictionary) AddWord(word string) {
this.data.Insert(word)
}
func (this *WordDictionary) Search(word string) bool {
return this.data.Search(word)
}
func main() {
wd := Constructor()
wd.AddWord("a")
wd.AddWord("a")
println(wd.Search("."))
println(wd.Search("a"))
println(wd.Search("aa"))
println(wd.Search("a"))
println(wd.Search(".a"))
println(wd.Search("a."))
}
/**
* Your WordDictionary object will be instantiated and called as such:
* obj := Constructor();
* obj.AddWord(word);
* param_2 := obj.Search(word);
*/