每日一题 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 ;
    }
};
相关推荐
枫景Maple8 小时前
LeetCode 2297. 跳跃游戏 VIII(中等)
算法·leetcode
緈福的街口12 小时前
【leetcode】3. 无重复字符的最长子串
算法·leetcode·职场和发展
小刘不想改BUG15 小时前
LeetCode 70 爬楼梯(Java)
java·算法·leetcode
sz66cm17 小时前
LeetCode刷题 -- 542. 01矩阵 基于 DFS 更新优化的多源最短路径实现
leetcode·矩阵·深度优先
爱coding的橙子19 小时前
每日算法刷题Day24 6.6:leetcode二分答案2道题,用时1h(下次计时20min没写出来直接看题解,节省时间)
java·算法·leetcode
慢慢慢时光19 小时前
leetcode sql50题
算法·leetcode·职场和发展
pay顿19 小时前
力扣LeetBook数组和字符串--二维数组
算法·leetcode
岁忧19 小时前
(nice!!!)(LeetCode每日一题)2434. 使用机器人打印字典序最小的字符串(贪心+栈)
java·c++·算法·leetcode·职场和发展·go
Tisfy19 小时前
LeetCode 2434.使用机器人打印字典序最小的字符串:贪心(栈)——清晰题解
leetcode·机器人·字符串·题解·贪心·