码迷,mamicode.com
首页 > 其他好文 > 详细

395. Longest Substring with At Least K Repeating Characters

时间:2017-10-17 15:15:41      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:aabb   思路   least   ++   bsp   cto   class   repeat   cte   

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

标签:aabb   思路   least   ++   bsp   cto   class   repeat   cte   

原文地址:http://www.cnblogs.com/tsunami-lj/p/7681070.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!