【双指针】LeetCode 395. 至少有 K 个重复字符的最长子串

题目链接

395. 至少有 K 个重复字符的最长子串

思路

代码

class Solution {
    public int longestSubstring(String s, int k) {
        int ans = 0;
        int len = s.length();
        char[] cs = s.toCharArray();
        int[] cnt = new int[26];

        for(int curKind = 1; curKind <= 26; curKind++){
            //对于限定的字符数量的条件下进行滑动窗口
            Arrays.fill(cnt, 0);
            int left = 0;
            int right = 0;
            //totalKind:窗口内所有字符类型数量,sumKind:窗口内满足出现次数不少于k的字符类型数量
            int totalKind = 0;
            int sumKind = 0;
            while(right < len){
                int rightIndex = cs[right] - 'a';
                cnt[rightIndex]++;
                if(cnt[rightIndex] == 1){
                    totalKind++;
                }
                if(cnt[rightIndex] == k){
                    sumKind++;
                }
                //当总字符种类数量不满足限定的字符种类数量,需要被迫移动左指针来减少总字符种类数量
                while(totalKind > curKind){
                    int leftIndex = cs[left] - 'a';
                    if(cnt[leftIndex] == 1){
                        totalKind--;
                    }
                    if(cnt[leftIndex] == k){
                        sumKind--;
                    }
                    cnt[leftIndex]--;
                    left++;
                }
                if(totalKind == sumKind){
                    ans = Math.max(ans, right - left + 1);
                }
                //主动移动右指针
                right++;
            }
        }

        return ans;
    }
}
posted @ 2023-05-16 09:53  Frodo1124  阅读(24)  评论(0编辑  收藏  举报