1. 程式人生 > >395. Longest Substring with At Least K Repeating Characters

395. Longest Substring with At Least K Repeating Characters

nbsp vector 條件 str app appear start input eve

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