Find the length of the longest substring T of a given string (consists of lowercase letters only) such that every character in T appears no less than k times.
Example 1:
Input:
s = "aaabb", k = 3
Output:
3
The longest substring is "aaa", as 'a' is repeated 3 times.
Example 2:
Input:
s = "ababbc", k = 2
Output:
5
The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.
Solution
class Solution {
public:
int longestSubstring(const string &s, const int k) {
if (s.empty() || s.size() < k) return 0;
return longestSubstring(s, k, 0, s.size() - 1);
}
int longestSubstring(const string &s, const int k, int begin, int end) {
const int n = end - begin + 1;
if (n < k) return 0;
int counter[26] = {0};
for (int i = begin; i <= end; ++i) ++counter[s[i] - 'a'];
bool found = true;
for (int i = begin; i <= end; ++i) {
if (counter[s[i] - 'a'] < k) {
found = false; break;
}
}
if (found) return n;
// found = false;
int l = 0, r = 0;
int max_len = 0;
for (int i = begin; i <= end; ++i) {
if (counter[s[i] - 'a'] < k) continue;
if (!found) {
found = true;
l = r = i;
} else {
r = i;
}
if (i == end || counter[s[i + 1] - 'a'] < k) {
max_len = max(max_len, longestSubstring(s, k, l, r));
found = false;
}
}
return max_len;
}
};