Skip to content

Commit 4130c51

Browse files
committed
solved: 211. Design Add and Search Words Data Structure
1 parent 5bcedfc commit 4130c51

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package main
2+
3+
type WordDictionary struct {
4+
children [26]* WordDictionary
5+
isWord bool
6+
7+
}
8+
9+
10+
func Constructor() WordDictionary {
11+
return WordDictionary{}
12+
}
13+
14+
15+
func (this *WordDictionary) AddWord(word string) {
16+
root := this
17+
18+
for _,item := range word{
19+
char := item - 'a'
20+
21+
if root.children[char] == nil {
22+
root.children[char] = &WordDictionary{}
23+
}
24+
root = root.children[char]
25+
}
26+
root.isWord = true
27+
28+
}
29+
30+
31+
func (this *WordDictionary) Search(word string) bool {
32+
root := this
33+
for i,item := range word{
34+
if word[i] == '.'{
35+
for _,item := range root.children{
36+
if item != nil && item.Search(word[i+1:]) {
37+
return true
38+
}
39+
}
40+
41+
return false
42+
}
43+
44+
char := item - 'a'
45+
if root.children[char] == nil{
46+
return false
47+
}
48+
root = root.children[char]
49+
}
50+
51+
return root.isWord
52+
}

0 commit comments

Comments
 (0)