-
Notifications
You must be signed in to change notification settings - Fork 1
/
word_dictionary.go
56 lines (48 loc) · 953 Bytes
/
word_dictionary.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
package _211_design_add_and_search_words_data_structure
type trie struct {
children [26]*trie
isEnd bool
}
func (t *trie) contains(word string) bool {
if len(word) == 0 {
return t.isEnd
}
first, rest := word[0], word[1:]
if first == '.' {
for _, child := range t.children {
if child != nil {
if child.contains(rest) {
return true
}
}
}
return false
}
idx := first - 'a'
if t.children[idx] == nil {
return false
}
return t.children[idx].contains(rest)
}
type WordDictionary struct {
root *trie
}
func Constructor() WordDictionary {
return WordDictionary{
root: &trie{},
}
}
func (wd *WordDictionary) AddWord(word string) {
cur := wd.root
for i := 0; i < len(word); i++ {
idx := word[i] - 'a'
if cur.children[idx] == nil {
cur.children[idx] = &trie{}
}
cur = cur.children[idx]
}
cur.isEnd = true
}
func (wd *WordDictionary) Search(word string) bool {
return wd.root.contains(word)
}