classnode { public: node* child[26]; bool isWord; node():isWord(false) { for(auto& p : child) p = nullptr; } ~node() { for(auto& p : child) delete p; } };
classWordDictionary { public: /** Initialize your data structure here. */ WordDictionary() { root = new node(); } ~WordDictionary() { delete root; } /** Adds a word into the data structure. */ voidaddWord(string word){ auto ptr = root; for(auto c : word) { int index = c - 'a'; if(!ptr->child[index]) ptr->child[index] = new node(); ptr = ptr->child[index]; } ptr->isWord = true; } /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */ boolsearch(string word){ return exist(word, 0, root); } boolexist(string& word, int pos, node* ptr) { if(!ptr) returnfalse; if(pos == word.size()) return ptr->isWord; auto c = word[pos]; if(c != '.') return exist(word, ++pos, ptr->child[c - 'a']); for(auto& child : ptr->child) if(exist(word, pos + 1, child)) returntrue; returnfalse; }
classTrieNode { public: TrieNode* child[26]; bool isWord; TrieNode() : isWord(false) { for(auto& p : child) p = nullptr; } ~TrieNode() { for(auto& p : child) delete p; } };
classWordDictionary { public: /** Initialize your data structure here. */ WordDictionary() { root = new TrieNode(); } ~WordDictionary() { delete root; } /** Adds a word into the data structure. */ voidaddWord(string word){ auto p = root; for(auto c : word) { if(!p->child[c - 'a']) p->child[c - 'a'] = new TrieNode(); p = p->child[c - 'a']; } p->isWord = true; } /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */ boolsearch(string word){ return exist(word, 0, root); } boolexist(string& word, int pos, TrieNode* p) { if(!p) returnfalse; if(pos == word.size()) return p->isWord; auto c = word[pos]; if(c != '.') return exist(word, ++pos, p->child[c - 'a']); for(auto& child : p->child) if(exist(word, (++pos)--, child)) returntrue; returnfalse; }