-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path890-find-and-replace-pattern.cpp
More file actions
28 lines (28 loc) · 967 Bytes
/
Copy path890-find-and-replace-pattern.cpp
File metadata and controls
28 lines (28 loc) · 967 Bytes
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
class Solution {
public:
vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
auto idGenerator = [](string &a) -> vector<int> {
vector<int> res(size(a), -1);
int id = 0;
unordered_map<char, int> mapping;
for (int i = 0; i < size(a); i++) {
if (mapping.count(a[i])) res[i] = mapping[a[i]];
else {
mapping[a[i]] = id++;
res[i] = mapping[a[i]];
}
}
return res;
};
auto patternMapping = idGenerator(pattern);
vector<string> res;
for (auto word: words) {
auto currPattern = idGenerator(word);
int i = 0;
for (i = 0; i < size(currPattern); i++)
if (currPattern[i] != patternMapping[i]) break;
if (i == size(currPattern)) res.push_back(word);
}
return res;
}
};