每日一题 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 ;
    }
};
相关推荐
Morwit1 分钟前
【力扣hot100】 1. 两数之和
数据结构·c++·算法·leetcode·职场和发展
py有趣9 分钟前
力扣热门100题之岛屿的数量(DFS/BFS经典题)
leetcode·深度优先·宽度优先
qinian_ztc1 小时前
frida 14.2.18 安装报错解决
算法·leetcode·职场和发展
田梓燊3 小时前
2026/4/11 leetcode 3741
数据结构·算法·leetcode
小肝一下5 小时前
每日两道力扣,day8
c++·算法·leetcode·哈希算法·hot100
语戚7 小时前
力扣 51. N 皇后:基础回溯、布尔数组优化、位运算全解(Java 实现)
java·算法·leetcode·力扣·剪枝·回溯·位运算
py有趣7 小时前
力扣热门100题之螺旋矩阵
算法·leetcode
人道领域7 小时前
【LeetCode刷题日记】383 赎金信
算法·leetcode·职场和发展
旖-旎7 小时前
哈希表(存在重复元素)(3)
数据结构·c++·学习·算法·leetcode·散列表
Tisfy8 小时前
LeetCode 3740.三个相等元素之间的最小距离 I:今日先暴力,“明日“再哈希
算法·leetcode·哈希算法·题解·模拟·遍历·暴力