-
Notifications
You must be signed in to change notification settings - Fork 0
/
question64.go
51 lines (43 loc) · 894 Bytes
/
question64.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
package chapter10
type MagicDictionary interface {
buildDict(words []string)
search(word string) bool
}
type magicDictionary struct {
root node
}
func (m *magicDictionary) buildDict(words []string) {
for _, word := range words {
curr := &m.root
for _, w := range word {
i := w - 'a'
n := curr.children[i]
if n == nil {
n = &node{}
curr.children[i] = n
}
curr = n
}
curr.isWord = true
}
}
func (m *magicDictionary) search(word string) bool {
return innerSearch(&m.root, word, false)
}
func innerSearch(curr *node, word string, edited bool) bool {
for i, w := range word {
if curr.children[w-'a'] != nil {
curr = curr.children[w-'a']
continue
}
if edited {
return false
}
for _, child := range curr.children {
if child != nil && innerSearch(child, word[i+1:], true) {
return true
}
}
}
return curr.isWord && edited
}