每日一题 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 ;
    }
};
相关推荐
LuckyLay40 分钟前
LeetCode算法题(Go语言实现)_39
算法·leetcode·golang
Tisfy1 小时前
LeetCode 2843.统计对称整数的数目:字符串数字转换
算法·leetcode·字符串·题解
一只_程序媛3 小时前
【leetcode hot 100 300】最长递增子序列
算法·leetcode·职场和发展
梭七y5 小时前
【力扣hot100题】(080)爬楼梯
算法·leetcode·职场和发展
Ludicrouers5 小时前
【Leetcode-Hot100】移动零
算法·leetcode·职场和发展
rigidwill6665 小时前
LeetCode hot 100—最长回文子串
数据结构·c++·算法·leetcode·职场和发展
小开不是小可爱7 小时前
leetcode_383. 赎金信_java
java·数据结构·算法·leetcode
Allen Wurlitzer10 小时前
算法刷题记录——LeetCode篇(1.8) [第71~80题](持续更新)
算法·leetcode·职场和发展
熬夜造bug14 小时前
LeetCode Hot100 刷题笔记(1)—— 哈希、双指针、滑动窗口
笔记·leetcode·hot100
不吃元西17 小时前
leetcode 74. 搜索二维矩阵
算法·leetcode·矩阵