classMagicDictionary { private: TrieNode* root; public: /** Initialize your data structure here. */ MagicDictionary() { root = new TrieNode(); } /** Build a dictionary through a list of words */ voidbuildDict(vector<string> dict){ for (auto& item: dict) { TrieNode* traverse = root; for (int i = 0; i < item.size(); ++i) { auto iter = traverse->mapping.find(item[i]); if (iter == traverse->mapping.end()) traverse->mapping[item[i]] = new TrieNode(); traverse = traverse->mapping[item[i]]; } traverse->endFlag = true; } return; } /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */ boolsearch(string word){ bool success = false; helper(false, root, 0, word, success); return success; } voidhelper(bool tag, TrieNode* cur, int index, string& word, bool& success){ if (index == word.size()) { if (tag == true && cur->endFlag == true) success = true; return; } for (auto& item : cur->mapping) { if (item.first != word[index] && tag == false) { helper(true, item.second, index + 1, word, success); } if (item.first == word[index]) { helper(tag, item.second, index + 1, word, success); } } return; } };
/** * Your MagicDictionary object will be instantiated and called as such: * MagicDictionary obj = new MagicDictionary(); * obj.buildDict(dict); * bool param_2 = obj.search(word); */