每日一题 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 ;
    }
};
相关推荐
We་ct14 分钟前
LeetCode 300. 最长递增子序列:两种解法从入门到优化
开发语言·前端·javascript·算法·leetcode·typescript
始三角龙1 小时前
LeetCode hoot 100 -- 找到字符串中的所有字母异位词
算法·leetcode·职场和发展
abant21 小时前
leetcode 45 跳跃问题2 很难的贪心
算法·leetcode·职场和发展
水木流年追梦3 小时前
CodeTop Top 100 热门题目(按题型分类)
算法·leetcode
Tisfy3 小时前
LeetCode 1722.执行交换操作后的最小汉明距离:连通图
算法·leetcode·dfs·题解·深度优先搜索·连通图
样例过了就是过了3 小时前
LeetCode热题100 杨辉三角
c++·算法·leetcode·动态规划
eggrall3 小时前
Leetcode 最大连续 1 的个数 III(medium)
算法·leetcode·职场和发展
Pentane.3 小时前
【力扣hot100】【Leetcode 54】螺旋矩阵|边界控制 算法笔记及打卡(19/100)
算法·leetcode·矩阵
米粒13 小时前
力扣算法刷题Day 49(接雨水)
算法·leetcode·职场和发展
6Hzlia4 小时前
【Hot 100 刷题计划】 LeetCode 155. 最小栈 | C++ 打包状态法 (最优雅的 O(1) 检索)
java·c++·leetcode