forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
implement-magic-dictionary.cpp
82 lines (69 loc) · 2.41 KB
/
implement-magic-dictionary.cpp
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Time: O(n), n is the length of the word
// Space: O(d)
class MagicDictionary {
public:
/** Initialize your data structure here. */
MagicDictionary() {
}
/** Build a dictionary through a list of words */
void buildDict(vector<string> dict) {
string result;
for (const auto& s : dict) {
trie_.Insert(s);
}
}
/** 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 find(word, &trie_, 0, true);
}
private:
struct TrieNode {
bool isString = false;
unordered_map<char, TrieNode *> leaves;
void Insert(const string& s) {
auto* p = this;
for (const auto& c : s) {
if (p->leaves.find(c) == p->leaves.cend()) {
p->leaves[c] = new TrieNode;
}
p = p->leaves[c];
}
p->isString = true;
}
~TrieNode() {
for (auto& kv : leaves) {
if (kv.second) {
delete kv.second;
}
}
}
};
bool find(const string& word, TrieNode *curr, int i, bool mistakeAllowed) {
if (i == word.length()) {
return curr->isString && !mistakeAllowed;
}
if (!curr->leaves.count(word[i])) {
return mistakeAllowed ?
any_of(curr->leaves.begin(), curr->leaves.end(),
[&](const pair<char, TrieNode *>& kvp) {
return find(word, kvp.second, i + 1, false);
}) :
false;
}
if (mistakeAllowed) {
return find(word, curr->leaves[word[i]], i + 1, true) ||
any_of(curr->leaves.begin(), curr->leaves.end(),
[&](const pair<char, TrieNode *>& kvp) {
return kvp.first != word[i] && find(word, kvp.second, i + 1, false);
});
}
return find(word, curr->leaves[word[i]], i + 1, false);
}
TrieNode trie_;
};
/**
* Your MagicDictionary object will be instantiated and called as such:
* MagicDictionary obj = new MagicDictionary();
* obj.buildDict(dict);
* bool param_2 = obj.search(word);
*/