classWordDictionary { public: structNode { bool is_end; Node* son[26]; Node () { is_end = false; for(int i = 0; i < 26; i ++) son[i] = NULL; } } *root;
WordDictionary() { root = newNode(); } voidaddWord(string word){ auto p = root; for(auto c : word) { int u = c - 'a'; if( !p->son[u]) p->son[u] = newNode(); p = p->son[u]; } p->is_end = true; } boolsearch(string word){ returndfs(root, word, 0); }
booldfs(Node* p, string& word, int i) { if( i == word.size()) return p->is_end; if( word[i] != '.') { int u = word[i] - 'a'; if( !p->son[u]) returnfalse; returndfs(p->son[u], word, i + 1); } else for(int j = 0; j < 26; j ++) { if(p->son[j] && dfs(p->son[j], word, i + 1)) returntrue; } returnfalse; } };
/** * Your WordDictionary object will be instantiated and called as such: * WordDictionary* obj = new WordDictionary(); * obj->addWord(word); * bool param_2 = obj->search(word); */