-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
smallest-substring-with-identical-characters-ii.cpp
90 lines (84 loc) · 2.51 KB
/
smallest-substring-with-identical-characters-ii.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Time: O(nlogn)
// Space: O(1)
// binary search, greedy
class Solution {
public:
int minLength(string s, int numOps) {
const auto& binary_search = [](int left, int right, const auto& check) {
while (left <= right) {
const int mid = left + (right - left) / 2;
if (check(mid)) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return left;
};
const auto& check = [&](int x) {
if (x == 1) {
int cnt = 0;
for (int i = 0; i < size(s); ++i) {
if (s[i] - '0' != i % 2) {
++cnt;
}
}
return min(cnt, static_cast<int>(size(s)) - cnt) <= numOps;
}
int total = 0;
for (int i = 0, cnt = 0; i < size(s); ++i) {
++cnt;
if (i + 1 == size(s) || s[i + 1] != s[i]) {
total += cnt / (x + 1);
cnt = 0;
}
}
return total <= numOps;
};
return binary_search(1, size(s), check);
}
};
// Time: O(nlogn)
// Space: O(n)
// binary search, greedy
class Solution2 {
public:
int minLength(string s, int numOps) {
const auto& binary_search = [](int left, int right, const auto& check) {
while (left <= right) {
const int mid = left + (right - left) / 2;
if (check(mid)) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return left;
};
vector<int> arr;
const auto& check = [&](int x) {
if (x == 1) {
int cnt = 0;
for (int i = 0; i < size(s); ++i) {
if (s[i] - '0' != i % 2) {
++cnt;
}
}
return min(cnt, static_cast<int>(size(s)) - cnt) <= numOps;
}
int cnt = 0;
for (const auto& l : arr) {
cnt += l / (x + 1);
}
return cnt <= numOps;
};
for (int i = 0, cnt = 0; i < size(s); ++i) {
++cnt;
if (i + 1 == size(s) || s[i + 1] != s[i]) {
arr.emplace_back(cnt);
cnt = 0;
}
}
return binary_search(1, size(s), check);
}
};