-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path2452.cpp
More file actions
84 lines (82 loc) · 2.2 KB
/
2452.cpp
File metadata and controls
84 lines (82 loc) · 2.2 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
class Solution {
public:
vector<string> twoEditWords(vector<string>& queries, vector<string>& dictionary) {
vector<string> res;
for (auto& query : queries) {
for (auto& word : dictionary) {
int diff = 0;
int n = query.size();
for (int i = 0; i < n; ++i) {
if (query[i] != word[i]) diff++;
}
if (diff <= 2) {
res.push_back(query);
break;
}
}
}
return res;
}
};
class TrieNode {
public:
vector<TrieNode*> children;
bool isEnd;
TrieNode() {
children.resize(26, nullptr);
isEnd = false;
}
};
class Trie {
private:
TrieNode* root = nullptr;
public:
Trie() {
root = new TrieNode();
}
void add(string s) {
TrieNode* node = root;
for (auto& c : s) {
if (!node->children[c - 'a']) {
node->children[c - 'a'] = new TrieNode();
}
node = node->children[c - 'a'];
}
node->isEnd = true;
}
bool find(string s) {
TrieNode* node = root;
return _find(s, 0, node, 0);
}
bool _find(string& s, int index, TrieNode* node, int cnt) {
if (cnt > 2) return false;
if (index == s.size() && node->isEnd) return true;
bool feasible = false;
if (node->children[s[index] - 'a']) {
if (_find(s, index + 1, node->children[s[index] - 'a'], cnt)) feasible = true;
}
if (!feasible) {
for (int i = 0; i < 26; ++i) {
if (node->children[i] != nullptr && _find(s, index + 1, node->children[i], cnt + 1)) {
feasible = true;
break;
}
}
}
return feasible;
}
};
class Solution {
public:
vector<string> twoEditWords(vector<string>& queries, vector<string>& dictionary) {
Trie* trie = new Trie();
for (auto& s : dictionary) {
trie->add(s);
}
vector<string> res;
for (auto& q : queries) {
if (trie->find(q)) res.push_back(q);
}
return res;
}
};