-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathWordDictionary.go
More file actions
108 lines (91 loc) · 2.36 KB
/
Copy pathWordDictionary.go
File metadata and controls
108 lines (91 loc) · 2.36 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/* https://leetcode.com/problems/add-and-search-word-data-structure-design/description/
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.
For example:
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true
Note:
You may assume that all words are consist of lowercase letters a-z.
You should be familiar with how a Trie works. If not, please work on this problem: Implement Trie (Prefix Tree) first.
*/
package ldesign
type wdNode struct {
Val byte
IsEnd bool
Next map[byte]*wdNode
}
// WordDictionary based on trie.
type WordDictionary struct {
root *wdNode
}
/** Initialize your data structure here. */
func WDConstructor() WordDictionary {
return WordDictionary{root: &wdNode{Next: make(map[byte]*wdNode)}}
}
/** Adds a word into the data structure. */
func (this *WordDictionary) AddWord(word string) {
var (
rword = []byte(word)
curNode = this.root
tmp *wdNode
ok bool
)
for _, letter := range rword {
if tmp, ok = curNode.Next[letter]; !ok {
tmp = &wdNode{Val: letter, Next: make(map[byte]*wdNode)}
curNode.Next[letter] = tmp
}
curNode = tmp
}
curNode.IsEnd = true
}
func (this *WordDictionary) search(curNode *wdNode, word string) bool {
if len(word) == 0 {
return false
}
var (
rword = []byte(word)
ok bool
)
for i := 0; i < len(rword); i++ {
letter := rword[i]
if letter != '.' {
if curNode, ok = curNode.Next[letter]; !ok {
return false
}
continue
}
if i < len(rword)-1 {
for _, cur := range curNode.Next {
if this.search(cur, string(rword[i+1:])) == true {
return true
}
}
return false
}
for _, cur := range curNode.Next {
if cur.IsEnd == true {
return true
}
}
return false
}
return curNode.IsEnd
}
/** 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 {
return this.search(this.root, word)
}
/**
* Your WordDictionary object will be instantiated and called as such:
* obj := Constructor();
* obj.AddWord(word);
* param_2 := obj.Search(word);
*/