395. Longest Substring with At Least K Repeating Characters

Posted 为了更优秀的你,加油!

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
    }
};

 

以上是关于395. Longest Substring with At Least K Repeating Characters的主要内容,如果未能解决你的问题,请参考以下文章

395. Longest Substring with At Least K Repeating Characters

LeetCode 395. Longest Substring with At Least K Repeating Characters C#

leetcode395 Longest Substring with At Least K Repeating Characters

395 Longest Substring with At Least K Repeating Characters 至少有K个重复字符的最长子串

Longest Substring Without Repeating Characters

Longest Substring Without Repeating Characters