TrieNode() : isWord(false) { for(auto& a : child) { a = nullptr; } } };
classTrie { public: Trie() { root = newTrieNode(); } voidinsert(string word){ TrieNode *cur = root; for(int i = 0; i < word.size(); i++) { int id = word[i]-'a'; if(cur->child[id] == nullptr) cur->child[id] = newTrieNode(); cur = cur->child[id]; } cur->isWord = true; } boolsearch(string word){ TrieNode *cur = root; for(int i = 0; i < word.size(); i++) { int id = word[i]-'a'; if(cur->child[id] == nullptr) returnfalse; cur = cur->child[id]; } return cur->isWord; } boolstartsWith(string prefix){ TrieNode *cur = root; for(int i = 0; i < prefix.size(); i++) { int id = prefix[i]-'a'; if(cur->child[id] == nullptr) returnfalse; cur = cur->child[id]; } returntrue; } private: TrieNode* root; };
/** * Your Trie object will be instantiated and called as such: * Trie* obj = new Trie(); * obj->insert(word); * bool param_2 = obj->search(word); * bool param_3 = obj->startsWith(prefix); */
TrieNode *root; MagicDictionary() { root = newTrieNode(); } voidbuildDict(vector<string> dictionary){ for(int i = 0; i < dictionary.size(); i++) { insert(root, dictionary[i]); } } boolsearch(string searchWord){ returndfs(root, searchWord, 0, 0); } booldfs(TrieNode* root, string& word, int i, int edit){ if(root == nullptr) returnfalse; if(root->isWord==true && i==word.size() && edit==1) returntrue; if(i<word.size() && edit<=1){ bool found = false; for(int j = 0; j<26 && !found; j++) { int newEdit = (word[i]-'a' == j) ? edit : edit+1; found = dfs(root->child[j], word, i+1, newEdit); } return found; } returnfalse; } voidinsert(TrieNode* root, string& word){ TrieNode *cur = root; for(int i = 0; i < word.size(); i++) { int id = word[i]-'a'; if(cur->child[id] == nullptr) { cur->child[id] = newTrieNode(); } cur = cur->child[id]; } cur->isWord = true; } };
/** * Your MagicDictionary object will be instantiated and called as such: * MagicDictionary* obj = new MagicDictionary(); * obj->buildDict(dictionary); * bool param_2 = obj->search(searchWord); */