LeetCode

来源:互联网 发布:php从数据库读取数据 编辑:程序博客网 时间:2024/06/01 08:00

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 = 3Output:3The longest substring is "aaa", as 'a' is repeated 3 times.

Example 2:

Input:s = "ababbc", k = 2Output:5The 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;    }};


原创粉丝点击