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

找到给定字符串(由小写字符组成)中的最长子串 T , 要求 T 中的每一字符出现次数都不少于 k 。输出 T 的长度。
示例 1:
输入:
s = "aaabb", k = 3
输出:
3
最长子串为 "aaa" ,其中 'a' 重复了 3 次。
示例 2:
输入:
s = "ababbc", k = 2
输出:
5
最长子串为 "ababb" ,其中 'a' 重复了 2 次, 'b' 重复了 3 次。

详见:https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/description/

C++:

class Solution {
public:
    int longestSubstring(string s, int k) {
        int res=0,n=s.size(),i=0;
        while(i+k<=n)
        {
            int m[26]={0},mask=0,max_idx=i;
            for(int j=i;j<n;++j)
            {
                int t=s[j]-'a';
                ++m[t];
                if(m[t]<k)
                {
                    mask|=(1<<t);
                }
                else
                {
                    mask&=(~(1<<t));
                }
                if(mask==0)
                {
                    res=max(res,j-i+1);
                    max_idx=j;
                }
            }
            i=max_idx+1;
        }
        return res;
    }
};

 参考:https://www.cnblogs.com/grandyang/p/5852352.html

posted on 2018-04-15 23:11  lina2014  阅读(145)  评论(0编辑  收藏  举报

导航