-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay_5 Add and Search Word.cpp
51 lines (46 loc) · 1.25 KB
/
Day_5 Add and Search Word.cpp
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
struct TrieNode{
bool isKey;
TrieNode* next[26];
TrieNode(){
isKey=false;
memset(next, NULL, sizeof(next));
}
};
class WordDictionary {
public:
WordDictionary() {
root = new TrieNode();
}
void addWord(string word) {
TrieNode* node = root;
for(auto c: word){
if(!node->next[c - 'a']) node->next[c - 'a'] = new TrieNode();
node = node->next[c - 'a'];
}
node->isKey = true;
}
bool search(string word) {
return helper(word, root);
}
private:
TrieNode* root;
bool helper(string word, TrieNode* node){
for(int i = 0; i < word.size(); i++){
char c = word[i];
if(c != '.'){
if(!node->next[c - 'a']) return false;
node = node->next[c - 'a'];
}
else{
bool found = false;
int j = 0;
for(; j < 26; j++){
if(node->next[j]) found |= helper(word.substr(i + 1), node->next[j]);
if(found) return true;
}
if(j == 26) return false;
}
}
return node->isKey;
}
};