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;
    }
};
相关推荐
MadPrinter16 分钟前
Python 异步爬虫实战:FindQC 商品数据爬取系统完整教程
爬虫·python·算法·自动化
郝学胜-神的一滴18 分钟前
Effective Modern C++ 条款36:如果有异步的必要请指定std::launch::async
开发语言·数据结构·c++·算法
小此方20 分钟前
Re:从零开始的 C++ STL篇(六)一篇文章彻底掌握C++stack&queue&deque&priority_queue
开发语言·数据结构·c++·算法·stl
0 0 029 分钟前
CCF-CSP 40-2 数字变换(transform)【C++】考点:预处理
开发语言·c++·算法
香芋Yu31 分钟前
【强化学习教程——01_强化学习基石】第06章_Q-Learning与SARSA
人工智能·算法·强化学习·rl·sarsa·q-learning
回敲代码的猴子35 分钟前
2月15日打卡
数据结构·算法
菜鸡儿齐1 小时前
leetcode-和为k的子数组
java·算法·leetcode
踩坑记录1 小时前
leetcode hot100 437. 路径总和 III medium 前缀和 DFS
leetcode
1 小时前
2.15最大效益,螺旋方阵,方块转化
算法
im_AMBER2 小时前
Leetcode 122 二叉树的最近公共祖先 | 二叉搜索树迭代器
学习·算法·leetcode·二叉树