-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplementMagicDictionary.cpp
More file actions
67 lines (58 loc) · 1.51 KB
/
ImplementMagicDictionary.cpp
File metadata and controls
67 lines (58 loc) · 1.51 KB
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
#include <bits/stdc++.h>
using namespace std;
class Trie {
public:
bool eow;
unordered_map<char, Trie *> children;
Trie() {
this->eow = false;
}
};
class MagicDictionary {
Trie *root;
public:
MagicDictionary() {
root = new Trie();
}
void buildDict(vector<string> dictionary) {
for (string &str : dictionary) insert(str);
}
bool search(string searchWord) {
return doSearch(searchWord, root);
}
private:
bool doSearch(string &str, Trie *node, bool change = false, int i = 0) {
if (!node) {
return false;
}
if (i == str.size()) {
return node->eow && change;
}
if (!node->children[str[i]] && change) {
return false;
}
bool found = false;
if (change) {
found = doSearch(str, node->children[str[i]], change, i + 1);
} else {
for (auto child : node->children) {
found |= doSearch(str, child.second, child.first != str[i], i + 1);
if (found) break;
}
}
return found;
}
void insert(string &str) {
int i = 0;
Trie *temp = root;
while (i < str.size()) {
if (!temp->children[str[i]])
temp->children[str[i]] = new Trie();
temp = temp->children[str[i]];
i++;
}
temp->eow = true;
}
};
int main() {
}