每日一题 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 ;
    }
};
相关推荐
1白天的黑夜13 小时前
哈希表-49.字母异位词分组-力扣(LeetCode)
c++·leetcode·哈希表
愚润求学5 小时前
【贪心算法】day7
c++·算法·leetcode·贪心算法
共享家95271 天前
优先搜索(DFS)实战
算法·leetcode·深度优先
flashlight_hi1 天前
LeetCode 分类刷题:2563. 统计公平数对的数目
python·算法·leetcode
楼田莉子1 天前
C++算法专题学习:栈相关的算法
开发语言·c++·算法·leetcode
dragoooon341 天前
[数据结构——lesson3.单链表]
数据结构·c++·leetcode·学习方法
轮到我狗叫了1 天前
力扣.1054距离相等的条形码力扣767.重构字符串力扣47.全排列II力扣980.不同路径III力扣509.斐波那契数列(记忆化搜索)
java·算法·leetcode
dragoooon341 天前
[优选算法专题二滑动窗口——串联所有单词的子串]
数据结构·c++·学习·算法·leetcode·学习方法
刃神太酷啦1 天前
C++ 异常处理机制:从基础到实践的全面解析----《Hello C++ Wrold!》(20)--(C/C++)
java·c语言·开发语言·c++·qt·算法·leetcode
薰衣草23331 天前
滑动窗口(2)——不定长
python·算法·leetcode