-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path211. Design Add and Search Words Data Structure
51 lines (47 loc) · 1.24 KB
/
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
50
51
class TrieNode{
public:
TrieNode *child[26];
bool end = false;
TrieNode(){
for(int i = 0; i < 26; i++)
child[i] = NULL;
}
};
class WordDictionary {
TrieNode *root ;
public:
WordDictionary() {
root = new TrieNode();
}
void addWord(string word) {
int idx = 0;
TrieNode * node = root;
for(char c: word) {
idx = c -'a';
if(!node->child[idx])
node->child[idx] = new TrieNode();
node = node->child[idx];
}
node->end = true;
}
bool search(string word) {
TrieNode *node = root;
return search(word, 0, node);
}
bool search(string &word, int idx , TrieNode *node ) {
if(!node) return 0;
if(idx == word.size()) return node->end;
if(word[idx] != '.')
return search(word, idx+1, node->child[word[idx]-'a']);
for(int key = 0; key< 26; key++)
if(search(word, idx+1, node->child[key]))
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);
*/