每日一题 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 ;
    }
};
相关推荐
YuTaoShao9 小时前
【LeetCode 热题 100】48. 旋转图像——转置+水平翻转
java·算法·leetcode·职场和发展
百年孤独_17 小时前
LeetCode 算法题解:链表与二叉树相关问题 打打卡
算法·leetcode·链表
算法_小学生17 小时前
LeetCode 75. 颜色分类(荷兰国旗问题)
算法·leetcode·职场和发展
算法_小学生17 小时前
LeetCode 287. 寻找重复数(不修改数组 + O(1) 空间)
数据结构·算法·leetcode
岁忧17 小时前
(LeetCode 每日一题) 1865. 找出和为指定值的下标对 (哈希表)
java·c++·算法·leetcode·go·散列表
alphaTao17 小时前
LeetCode 每日一题 2025/6/30-2025/7/6
算法·leetcode·职场和发展
ゞ 正在缓冲99%…17 小时前
leetcode67.二进制求和
算法·leetcode·位运算
YuTaoShao17 小时前
【LeetCode 热题 100】240. 搜索二维矩阵 II——排除法
java·算法·leetcode
Tanecious.20 小时前
LeetCode 876. 链表的中间结点
算法·leetcode·链表
Two_brushes.1 天前
【算法】宽度优先遍历BFS
算法·leetcode·哈希算法·宽度优先