395. Longest Substring with At Least K Repeating Characters

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.



class Solution {
public:
    //分治加递归
    int longestSubstring(string s, int k) {
        if(s.size()<k) return 0;
        vector<int> m(26,0);
        for(int i=0;i<s.size();i++){
            m[s[i]-'a']++;
        }
        bool flag = true;
        int j=0;
        for(j=0;j<s.size();j++){
            if(m[s[j]-'a']<k){
                flag = false;
                break;
            }
        }
        if( flag == true) return s.size();
        //否则以第一次出现不符合要求的s[i]的位置为分割,左右分治
        int res1 = longestSubstring(s.substr(0,j),k);
        int res2 = longestSubstring(s.substr(j+1),k);
        return max(res1,res2);
    }
};

 

posted on 2020-11-01 11:48  wsw_seu  阅读(52)  评论(0编辑  收藏  举报

导航