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;
    }
};
相关推荐
Fanxt_Ja14 小时前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下14 小时前
最终的信号类
开发语言·c++·算法
茉莉玫瑰花茶15 小时前
算法 --- 字符串
算法
博笙困了15 小时前
AcWing学习——差分
c++·算法
NAGNIP15 小时前
认识 Unsloth 框架:大模型高效微调的利器
算法
NAGNIP15 小时前
大模型微调框架之LLaMA Factory
算法
echoarts15 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Python技术极客15 小时前
一款超好用的 Python 交互式可视化工具,强烈推荐~
算法
徐小夕15 小时前
花了一天时间,开源了一套精美且支持复杂操作的表格编辑器tablejs
前端·算法·github
小刘鸭地下城15 小时前
深入浅出链表:从基础概念到核心操作全面解析
算法