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;
    }
};
相关推荐
-dzk-1 天前
【哈希】LC 49.字母异位词分组
算法·哈希算法
·醉挽清风·1 天前
学习笔记—算法—算法题
笔记·学习·算法
2401_854151551 天前
嵌入式传感器驱动开发深度解析——从 I2C/SPI 驱动到数据融合算法
驱动开发·算法
cpp_25011 天前
P6625 [省选联考 2020 B 卷] 卡牌游戏
数据结构·c++·算法·前缀和·贪心·洛谷题解·省选
石一峰6991 天前
驱动:私有数据为什么要在三个地方各挂一遍?
数据库·python·算法
卡提西亚1 天前
leetcode-179. 最大数
python·算法
浩瀚地学1 天前
【面试算法笔记】0302-哈希表-哈希表实现
java·经验分享·笔记·算法·面试
ECT-OS-JiuHuaShan1 天前
严格证明:还原论是ASCII,整体论是UTF-8的历史意义和价值
开发语言·人工智能·算法·量子计算
ShallWeL1 天前
【机器学习】(19)—— 数据特性与标签
人工智能·算法·机器学习
Frostnova丶1 天前
(17)LeetCode 41. 缺失的第一个正数
数据结构·算法·leetcode