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.
找出一个子串,使得每个字母最少重复k次
分治,先统计最长的串,若满足条件便返回;否则,找到不满足条件字母的位置,分别计算他左右的子串。如此递归下去。
class Solution {
public:
int longestSubstring(string s, int k) {
if (k > s.length()) return 0;
return solve(s, 0, s.length()-1, k);
}
int solve(string s, int st, int ed, int k) {
if (ed - st + 1 < k) return 0;
unordered_map<int, int> m(26);
for (int i = st; i <= ed; ++i) {
m[s[i]-'a']++;
}
for (auto x: m) {
if (x.second >= k) continue;
for (int i = st; i <= ed; ++i) {
if (s[i] == x.first + 'a') {
int le = solve(s, st, i-1, k);
int ri = solve(s, i+1, ed, k);
return max(le, ri);
}
}
}
return ed - st + 1;
}
};