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;
}
};
本文介绍了一种寻找字符串中每个字符至少重复k次的最长子串的算法。通过分治法实现,首先统计最长可能的子串长度,如果所有字符出现次数均大于等于k,则直接返回;否则,找到不符合条件的字符进行子串分割并递归求解。

1287

被折叠的 条评论
为什么被折叠?



