forked from fengvyi/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
890. Find and Replace Pattern.cpp
61 lines (57 loc) · 1.44 KB
/
890. Find and Replace Pattern.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
class Solution {
public:
vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
vector<string>res;
for (auto& s: words) {
if (isValid(s, pattern)) {
res.push_back(s);
}
}
return res;
}
bool isValid(string& a, string& b) {
unordered_map<char, char>m, t;
int n = a.size(), l = b.size();
if (n != l) {
return false;
}
for (int i = 0; i < n; ++i) {
if (m.count(a[i]) || t.count(b[i])) {
if (m[a[i]] == b[i] && t[b[i]] == a[i]) {
continue;
} else {
return false;
}
}
m[a[i]] = b[i];
t[b[i]] = a[i];
}
return true;
}
};
class Solution {
public:
vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
vector<string>res;
for (auto& s: words) {
if (normalize(s) == normalize(pattern)) {
res.push_back(s);
}
}
return res;
}
string normalize(string& s) {
unordered_map<char, char>m;
string res;
char c = 'a';
for (auto& x: s) {
if (!m.count(x)) {
m[x] = c++;
}
}
for (auto& x: s) {
res.push_back(m[x]);
}
return res;
}
};