Fork me on GitHub

Implement Magic Dictionary

Description

https://leetcode.com/problems/implement-magic-dictionary/description/

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class TrieNode {
public:
unordered_map<char, TrieNode*> mapping;
bool endFlag;
TrieNode() {
endFlag = false;
}
};

class MagicDictionary {
private:
TrieNode* root;
public:
/** Initialize your data structure here. */
MagicDictionary() {
root = new TrieNode();
}

/** Build a dictionary through a list of words */
void buildDict(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 */
bool search(string word) {
bool success = false;
helper(false, root, 0, word, success);
return success;
}

void helper(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);
*/