0%

211. Design Add and Search Words Data Structure

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
class WordDictionary {
struct TrieNode {
TrieNode *children[26] = {nullptr};
bool isEnd = false;
};

TrieNode *root = nullptr;

public:
/** Initialize your data structure here. */
WordDictionary() : root(new TrieNode) {

}

/** Adds a word into the data structure. */
void addWord(string word) {
auto p = root;
for (auto c : word) {
int k = c - 'a';
if (!p->children[k]) {
p->children[k] = new TrieNode;
}
p = p->children[k];
}
p->isEnd = true;
}

/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
bool search(string word) {
return search(word, 0, root);
}

bool search(const string &w, int i, TrieNode *p) {
if (!p) return false;
if (i == w.length()) return p->isEnd;
if (w[i] != '.') return search(w, i + 1, p->children[w[i] - 'a']);
for (int k = 0; k < 26; ++k) {
if (search(w, i + 1, p->children[k])) return true;
}
return false;
}
};

/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary* obj = new WordDictionary();
* obj->addWord(word);
* bool param_2 = obj->search(word);
*/