Implement Magic Dictionary
class MagicDictionary {
public:
class TrieNode {
public:
TrieNode() : isWord(false) {}
unordered_map
/** Initialize your data structure here. */
MagicDictionary() {
root = new TrieNode();
}
/** Build a dictionary through a list of words */
void buildDict(vector<string> dict) {
for (auto word: dict) {
insertWord(word);
}
}
/** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */
bool search(string word) {
return searchWord(root, 0, 0, word);
}
void insertWord(string word) {
TrieNode *cur = root;
for (auto ch: word) {
if (!cur->child[ch]) {
cur->child[ch] = new TrieNode();
}
cur = cur->child[ch];
}
cur->isWord = true;
}
bool searchWord(TrieNode *root, int start, int diff, string& word) {
if (start == word.size()) return diff == 1 && root->isWord;
if (root->child.count(word[start])) {
if (searchWord(root->child[word[start]], start+1, diff, word)) return true;
}
for (auto it: root->child) {
if (it.first == word[start]) continue;
if (searchWord(it.second, start+1, diff+1, word)) return true;
}
return false;
}
private: TrieNode *root; };