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 helper(const string &s, int start, int end, int k) {
        if(end - start < 1) return 0;
        vector<int>hash(26, 0);
        for(int i = start; i < end; i++) {
            hash[s[i]-'a']++;
        }
        for(int i = 0; i < 26; i++) {
            if(hash[i] && hash[i] < k ) {
                for(int j = start; j < end; j++){
                    if(s[j] == i + 'a') {
                         return max(helper(s, start, j, k), helper(s, j+1, end, k));
                    }
                }
            }
        }
        return end - start;
    }
    int longestSubstring(string s, int k) {
        return helper(s, 0, s.length(), k);
    }
};

 

posted @ 2017-10-17 12:54  Tsunami_lj  阅读(172)  评论(0编辑  收藏  举报