211. Design Add and Search Words Data Structure
class TrieNode {
public:
bool is_end;
vector<TrieNode*> children = vector<TrieNode*>(26, nullptr);
TrieNode() {
is_end = false; }
};
class WordDictionary {
public:
/** Initialize your data structure here. */
TrieNode* root = new TrieNode();
TrieNode* p;
WordDictionary() {
}
void addWord(string word) {
int len = word.size();
p = root;
for(int ii = 0; ii < len; ii++) {
if(!p->children[word[ii] - 'a']) p->children[word[ii] - 'a'] = new TrieNode();
p = p->children[word[ii] - 'a'];
}
p->is_end = true;
}
bool search(string word) {
int word_len = word.size();
queue<TrieNode*> Q;
Q.push(root);
int ii = 0;
for(; ii < word_len; ii++) {
int Q_len = Q.size();
int num = word[ii] - 'a';
for(int kk = 0; kk < Q_len; kk++) {
p = Q.front();
Q.pop();
if(word[ii] != '.') {
if(!p->children[num]) continue;
else Q.push(p->children[num]);
}
else for(int jj = 0; jj < 26; jj++) if(p->children[jj]) Q.push(p->children[jj]);
}
}
if(ii < word_len) return false;
while(!Q.empty()) {
p = Q.front();
Q.pop();
if(p->is_end) 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);
*/