leetcode 2516. 每种字符至少取 K 个

题目描述

滑动窗口问题

可以转化为求按照题目要求从两端取走字符后,中间部分的最大长度。中间部分就是一个滑动窗口。

cpp 复制代码
class Solution {
public:
    int takeCharacters(string s, int k) {
        vector<int> count(3,0);
        int n = s.size();
        for(int i = 0;i <n;i++){
            count[s[i] - 'a']++;
        }
        if(count[0] < k || count[1] < k || count[2] < k)
            return -1;

        int a_threshold = count[0] - k;
        int b_threshold = count[1] - k;
        int c_threshold = count[2] - k;

        int right = 0;
        int max_len = 0;
        int a_count = 0;
        int b_count = 0;
        int c_count = 0;

        for(int left = 0;left < n;left++){
            while(a_count <= a_threshold && b_count<= b_threshold && c_count<= c_threshold){
                max_len = max(max_len,right -left);//[left,right)
                if(right == n)
                    break;
                if(s[right] == 'a')  a_count++;
                if(s[right] == 'b')  b_count++;
                if(s[right] == 'c')  c_count++;
                right++;
            }
            if(s[left] == 'a') a_count--;
            if(s[left] == 'b') b_count--;
            if(s[left] == 'c') c_count--;
        }
        return n - max_len;
    }
};
相关推荐
码上发达24 分钟前
状态压缩搜索解法(DFS + Dominance)
算法
颜酱27 分钟前
差分数组:高效处理数组区间批量更新的核心技巧
javascript·后端·算法
yyy(十一月限定版)37 分钟前
图论——最小生成树Kruskal算法
算法·图论
宇木灵41 分钟前
C语言基础-十一、递归与分治(完结)
c语言·开发语言·学习·算法
We་ct1 小时前
LeetCode 173. 二叉搜索树迭代器:BSTIterator类 实现与解析
前端·算法·leetcode·typescript
weixin_395448911 小时前
main.c_0222cursor
c语言·前端·算法
Zik----2 小时前
Leetcode27 —— 移除元素(双指针)
数据结构·算法
踩坑记录2 小时前
leetcode hot100 79. 单词搜索 medium 递归回溯
leetcode
陆嵩2 小时前
GMRES 方法的数学推导及其算法表示
算法·概率论·arnoldi·gmres·minres·givens·hessenberg
plus4s2 小时前
2月22日(94-96题)
算法