Smallest Substring With Identical Characters II
Time complexity: $O(n\log n)$
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
|
#include <iostream>
#include <cstring>
#include <set>
class Solution {
public:
int minLength(std::string s, int numOps) {
int cnt0 = 0, cnt1 = 0, k = 0;
for (char c : s) {
k = 1 - k;
if (k == c - '0') {
++cnt0;
}
else {
++cnt1;
}
}
if (cnt0 <= numOps || cnt1 <= numOps) {
return 1;
}
int n = s.length();
int left = 2, right = n;
for (int mid = (left + right) / 2; right >= left; ) {
if (check(s, numOps, mid)) {
right = mid - 1;
}
else {
left = mid + 1;
}
mid = (left + right) / 2;
}
return left;
}
private:
int check(std::string& s, int numOps, int sublen) {
int curlen = 0;
char prev = s[0];
for (char c : s) {
if (c == prev) {
++curlen;
}
else {
numOps -= curlen / (sublen + 1);
curlen = 1;
prev = c;
}
}
numOps -= curlen / (sublen + 1);
return numOps >= 0;
}
};
|
