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;
    }
};
相关推荐
小欣加油1 小时前
leetcode 1576 替换所有的问号
c++·算法·leetcode·职场和发展
lifallen2 小时前
Caffeine TimerWheel时间轮 深度解析:O(1)复杂度增删和触发时间事件
java·数据结构·算法·缓存·中间件
Christo33 小时前
TFS-1996《The Possibilistic C-Means Algorithm: Insights and Recommendations》
人工智能·算法·机器学习
地平线开发者6 小时前
理想汽车智驾方案介绍专题 3 MoE+Sparse Attention 高效结构解析
人工智能·算法·自动驾驶
pusue_the_sun6 小时前
C语言强化训练(1)
c语言·开发语言·算法
一支鱼9 小时前
leetcode-2-两数相加
算法·leetcode·typescript
斯坦索尼11 小时前
关于 01 背包问题的简单解释,理解状态转移与继承的相似性
算法·01背包问题
学涯乐码堂主11 小时前
《信息学奥林匹克辞典》中的一个谬误
数据结构·c++·算法·青少年编程·排序算法·信奥·gesp 考试
一匹电信狗12 小时前
【C++】C++11新特性第一弹(列表初始化、新式声明、范围for和STL中的变化)
服务器·开发语言·c++·leetcode·小程序·stl·visual studio
我叫黑大帅13 小时前
从奶奶挑菜开始:手把手教你搞懂“TF-IDF”
人工智能·python·算法