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

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

使用滑动窗口来解决

cpp 复制代码
class Solution {
public:
    int longestSubstring(string s, int k) {
        
        // 枚举 所有情况 最多有26个字符 满足大于k 
        int n = s.size();
        int ans = 0;

        for(int unique = 1; unique <= 26;++unique)
        {
            vector<int> nums(26,0);
            int start = 0;
            int end = 0;
            int curUnique = 0;
            int curUniqueSumk = 0;
            while(end < s.size() && start <= end)
            {
                
                if(curUnique <= unique)
                {
                    int idx = s[end] - 'a';
                    if(nums[idx] == 0){
                        curUnique++;
                    }
                    nums[idx]++;
                    if(nums[idx] == k)
                    {
                        curUniqueSumk++;
                    }
                    ++end;
                }else{
                    int idx = s[start] - 'a' ;
                    nums[idx]--;
                    if(nums[idx] == 0){
                        curUnique--;
                    }
                    if(nums[idx] == k-1)
                    {
                        curUniqueSumk--;
                    }
                    ++start;
                }

                if(curUnique == unique && curUniqueSumk == unique)
                {
                    ans = max(ans,end - start);
                }
            }
        }
        return ans ;
    }
};
相关推荐
一匹电信狗20 小时前
【C++】异常详解(万字解读)
服务器·c++·算法·leetcode·小程序·stl·visual studio
墨染点香21 小时前
LeetCode 刷题【43. 字符串相乘】
算法·leetcode·职场和发展
Keying,,,,1 天前
力扣hot100 | 矩阵 | 73. 矩阵置零、54. 螺旋矩阵、48. 旋转图像、240. 搜索二维矩阵 II
python·算法·leetcode·矩阵
_不会dp不改名_1 天前
leetcode_42 接雨水
算法·leetcode·职场和发展
code小毛孩1 天前
leetcode hot100数组:缺失的第一个正数
数据结构·算法·leetcode
快去睡觉~1 天前
力扣400:第N位数字
数据结构·算法·leetcode
gzzeason2 天前
LeetCode Hot100:递归穿透值传递问题
算法·leetcode·职场和发展
qq_513970442 天前
力扣 hot100 Day74
数据结构·算法·leetcode
墨染点香2 天前
LeetCode 刷题【42. 接雨水】
算法·leetcode·职场和发展
এ᭄画画的北北2 天前
力扣-347.前K个高频元素
算法·leetcode