-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadd_search.go
57 lines (49 loc) · 1.37 KB
/
add_search.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
package problem0211
/*
Design a data structure that supports adding new words and finding if a string matches any previously added string.
Implement the WordDictionary class:
WordDictionary() Initializes the object.
void addWord(word) Adds word to the data structure, it can be matched later.
bool search(word) Returns true if there is any string in the data structure that matches word or false otherwise.
word may contain dots '.' where dots can be matched with any letter.
*/
type WordDictionary struct {
Next [26]*WordDictionary
IsWord bool
}
func Constructor() WordDictionary {
return WordDictionary{}
}
func (w *WordDictionary) AddWord(word string) {
var head = w
for i := range word {
if head.Next[word[i]-'a'] != nil {
head = head.Next[word[i]-'a']
} else {
head.Next[word[i]-'a'] = &WordDictionary{}
head = head.Next[word[i]-'a']
}
}
head.IsWord = true
}
func (w *WordDictionary) Search(word string) bool {
var searchHelper func(cur *WordDictionary, pos int) bool
searchHelper = func(cur *WordDictionary, pos int) bool {
if pos == len(word) {
return cur.IsWord
}
if word[pos] != '.' {
if n := cur.Next[word[pos]-'a']; n != nil {
return searchHelper(n, pos+1)
}
} else {
for _, n := range cur.Next {
if n != nil && searchHelper(n, pos+1) {
return true
}
}
}
return false
}
return searchHelper(w, 0)
}