forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
match-substring-after-replacement.cpp
59 lines (57 loc) · 1.82 KB
/
match-substring-after-replacement.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
// Time: O(n * k), n = len(s), k = len(sub)
// Space: O(m), m = len(mappings)
// brute force
class Solution {
public:
bool matchReplacement(string s, string sub, vector<vector<char>>& mappings) {
const auto& f = [](char c) {
return ::isdigit(c) ? c - '0' : (::islower(c) ? c - 'a' + 10 : c - 'A' + 36);
};
vector<vector<bool>> lookup(62, vector<bool>(62));
for (const auto& m : mappings) {
lookup[f(m[0])][f(m[1])] = true;
}
transform(begin(s), end(s), begin(s), f);
transform(begin(sub), end(sub), begin(sub), f);
const auto& check = [&](int i) {
for (int j = 0; j < size(sub); ++j) {
if (sub[j] != s[i + j] && (!lookup[sub[j]][s[i + j]])) {
return false;
}
}
return true;
};
for (int i = 0; i < size(s) - size(sub) + 1; ++i) {
if (check(i)) {
return true;
}
}
return false;
}
};
// Time: O(n * k), n = len(s), k = len(sub)
// Space: O(m), m = len(mappings)
// brute force
class Solution2 {
public:
bool matchReplacement(string s, string sub, vector<vector<char>>& mappings) {
unordered_map<char, unordered_set<char>> lookup;
for (const auto& m : mappings) {
lookup[m[0]].emplace(m[1]);
}
const auto& check = [&](int i) {
for (int j = 0; j < size(sub); ++j) {
if (sub[j] != s[i + j] && (!lookup.count(sub[j]) || !lookup[sub[j]].count(s[i + j]))) {
return false;
}
}
return true;
};
for (int i = 0; i < size(s) - size(sub) + 1; ++i) {
if (check(i)) {
return true;
}
}
return false;
}
};