forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maximum-number-of-removable-characters.cpp
74 lines (70 loc) · 1.93 KB
/
maximum-number-of-removable-characters.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
62
63
64
65
66
67
68
69
70
71
72
73
74
// Time: O(rlogn)
// Space: O(r)
// if r = O(1), this is better
class Solution {
public:
int maximumRemovals(string s, string p, vector<int>& removable) {
int left = 0, right = size(removable);
while (left <= right) {
int mid = left + (right - left) / 2;
if (!check(s, p, removable, mid)) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return right;
}
private:
bool check(const string& s, const string& p, const vector<int>& removable, int x) {
unordered_set<int> lookup;
for (int i = 0; i < x; ++i) {
lookup.emplace(removable[i]);
}
int j = 0;
for (int i = 0; i < size(s); ++i) {
if (lookup.count(i) || s[i] != p[j]) {
continue;
}
if (++j == size(p)) {
return true;
}
}
return false;
}
};
// Time: O(rlogn)
// Space: O(n)
// if r = O(n), this is better
class Solution2 {
public:
int maximumRemovals(string s, string p, vector<int>& removable) {
vector<int> lookup(size(s), numeric_limits<int>::max());
for (int i = 0; i < size(removable); ++i) {
lookup[removable[i]] = i + 1;
}
int left = 0, right = size(removable);
while (left <= right) {
int mid = left + (right - left) / 2;
if (!check(s, p, lookup, mid)) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return right;
}
private:
bool check(const string& s, const string& p, const vector<int>& lookup, int x) {
int j = 0;
for (int i = 0; i < size(s); ++i) {
if (lookup[i] <= x || s[i] != p[j]) {
continue;
}
if (++j == size(p)) {
return true;
}
}
return false;
}
};