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;
    }
};
相关推荐
HAPPY酷17 分钟前
std::pair` 与 `std::map` 基础
开发语言·c++·算法
喜欢吃燃面31 分钟前
基础算法:高精度
开发语言·c++·学习·算法
努力学算法的蒟蒻1 小时前
day84(2.12)——leetcode面试经典150
算法·leetcode·面试
程序员酥皮蛋1 小时前
hot 100 第二十三题 23.反转链表
数据结构·算法·leetcode·链表
TracyCoder1231 小时前
LeetCode Hot100(51/100)——155. 最小栈
数据结构·算法·leetcode
wu_asia1 小时前
每日一练叁
算法
dalong101 小时前
A24:圈住小猫游戏
笔记·算法·游戏·aardio
Y.O.U..1 小时前
力扣刷题-86.分隔链表
算法·leetcode·链表
智算菩萨1 小时前
上下文学习的贝叶斯推断视角:隐式梯度下降还是隐式贝叶斯?
人工智能·算法
TracyCoder1232 小时前
LeetCode Hot100(52/100)——394. 字符串解码
算法·leetcode·职场和发展