forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.go
62 lines (54 loc) · 1.06 KB
/
Solution.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
type WordDictionary struct {
root *trie
}
func Constructor() WordDictionary {
return WordDictionary{new(trie)}
}
func (this *WordDictionary) AddWord(word string) {
this.root.insert(word)
}
func (this *WordDictionary) Search(word string) bool {
n := len(word)
var dfs func(int, *trie) bool
dfs = func(i int, cur *trie) bool {
if i == n {
return cur.isEnd
}
c := word[i]
if c != '.' {
child := cur.children[c-'a']
if child != nil && dfs(i+1, child) {
return true
}
} else {
for _, child := range cur.children {
if child != nil && dfs(i+1, child) {
return true
}
}
}
return false
}
return dfs(0, this.root)
}
type trie struct {
children [26]*trie
isEnd bool
}
func (t *trie) insert(word string) {
cur := t
for _, c := range word {
c -= 'a'
if cur.children[c] == nil {
cur.children[c] = new(trie)
}
cur = cur.children[c]
}
cur.isEnd = true
}
/**
* Your WordDictionary object will be instantiated and called as such:
* obj := Constructor();
* obj.AddWord(word);
* param_2 := obj.Search(word);
*/