forked from wufenggirl/LeetCode-in-Golang
-
Notifications
You must be signed in to change notification settings - Fork 2
/
add-and-search-word-data-structure-design.go
executable file
·71 lines (59 loc) · 1.23 KB
/
add-and-search-word-data-structure-design.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
package problem0211
type WordDictionary struct {
sons [26]*WordDictionary
end int
}
/** Initialize your data structure here. */
func Constructor() WordDictionary {
return WordDictionary{}
}
/** Adds a word into the data structure. */
func (this *WordDictionary) AddWord(word string) {
for _, b := range word {
idx := b - 'a'
if this.sons[idx] == nil {
this.sons[idx] = &WordDictionary{}
}
this = this.sons[idx]
}
this.end++
}
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
func (this *WordDictionary) Search(word string) bool {
for i, b := range word {
if b != '.' {
idx := b - 'a'
if this.sons[idx] == nil {
return false
}
this = this.sons[idx]
} else {
for _, son := range this.sons {
if son == nil {
continue
}
this = son
if i == len(word)-1 {
if this.end > 0 {
return true
}
continue
}
if this.Search(word[i+1:]) {
return true
}
}
return false
}
}
if this.end > 0 {
return true
}
return false
}
/**
* Your WordDictionary object will be instantiated and called as such:
* obj := Constructor();
* obj.AddWord(word);
* param_2 := obj.Search(word);
*/