您的位置:首页 > 其它

LeetCode - 395 - Longest Substring with At Least K Repeating Characters

2017-08-11 17:06 459 查看
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: