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;
    }
};
相关推荐
贺函不是涵10 分钟前
【沉浸式求职学习day46】【华为5.7暑期机试题目讲解】
学习·算法·华为
June`17 分钟前
FloodFill算法:洪水般的图像处理艺术
算法·深度优先
珂朵莉MM41 分钟前
2023 睿抗机器人开发者大赛CAIP-编程技能赛-本科组(国赛) 解题报告 | 珂学家
人工智能·算法·职场和发展·深度优先·图论
JANYI20182 小时前
C语言经典面试题及答案100道
linux·c语言·c++·算法·ubuntu·面试
机器学习之心HML2 小时前
分类预测 | Matlab实现PSO-RF粒子群算法优化随机森林多特征分类预测
算法·matlab·分类
姬公子5212 小时前
leetcode hot100刷题日记——8.合并区间
算法·leetcode·职场和发展
阳洞洞2 小时前
leetcode 25. Reverse Nodes in k-Group
leetcode·链表·list
鱼糕权八郎 -2 小时前
LeetCode222_完全二叉树的结点个数
c++·leetcode
袁气满满~_~2 小时前
回溯算法——排列篇
算法·leetcode
暮乘白帝过重山2 小时前
JVM之GC常见的垃圾回收器
java·jvm·算法