-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathlongest-substring-with-at-least-k-repeating-characters.cc
More file actions
57 lines (53 loc) · 1.24 KB
/
longest-substring-with-at-least-k-repeating-characters.cc
File metadata and controls
57 lines (53 loc) · 1.24 KB
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
// Longest Substring with At Least K Repeating Characters
/// O(n |alphabet|)
class Solution {
public:
int longestSubstring(string s, int k) {
const int AB = 26;
int r = 0, c[AB];
for (int u = 1; u <= AB; u++) {
fill_n(c, AB, 0);
int unique = 0, geq_k = 0;
for (int i = 0, j = 0; j < s.size(); ) {
if (unique <= u) {
int& c0 = c[s[j]-'a'];
if (! c0)
unique++;
if (++c0 == k)
geq_k++;
j++;
} else {
int& c0 = c[s[i]-'a'];
if (c0 == k)
geq_k--;
if (! --c0)
unique--;
i++;
}
if (unique == u && geq_k == u)
r = max(r, j-i);
}
}
return r;
}
};
/// O(n |alphabet|)
class Solution {
static const int AB = 26;
int f(const string& s, int l, int r, int k) {
int ret = 0, c[AB] = {}, b = l;
for (int i = l; i < r; i++)
c[s[i]-'a']++;
for (int i = l; i < r; i++)
if (c[s[i]-'a'] < k) {
if (b < i)
ret = max(ret, f(s, b, i, k));
b = i+1;
}
return b == l ? r-l : b < r ? max(ret, f(s, b, r, k)) : ret;
}
public:
int longestSubstring(string s, int k) {
return f(s, 0, s.size(), k);
}
};