forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0211-design-add-and-search-words-data-structure.go
53 lines (44 loc) · 1.24 KB
/
0211-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
type TrieNode struct {
children map[byte]*TrieNode
word bool
}
type WordDictionary struct {
root *TrieNode
}
func Constructor() WordDictionary {
return WordDictionary{root: &TrieNode{children: make(map[byte]*TrieNode)}}
}
func (this *WordDictionary) AddWord(word string) {
cur := this.root
for c := 0; c < len(word); c++ {
if _, ok := cur.children[word[c]]; !ok {
cur.children[word[c]] = &TrieNode{children: make(map[byte]*TrieNode)}
}
cur = cur.children[word[c]]
}
cur.word = true
}
func (this *WordDictionary) Search(word string) bool {
var dfs func(int, *TrieNode) bool
dfs = func(j int, root *TrieNode) bool {
cur := root
for i := j; i < len(word); i++ {
c := word[i]
if c == '.' {
for _, child := range cur.children {
if dfs(i + 1, child) {
return true
}
}
return false
} else {
if _, ok := cur.children[c]; !ok {
return false
}
cur = cur.children[c]
}
}
return cur.word
}
return dfs(0, this.root)
}