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;
    }
};
相关推荐
DoraBigHead33 分钟前
小哆啦解题记——异位词界的社交网络
算法
木头左2 小时前
逻辑回归的Python实现与优化
python·算法·逻辑回归
lifallen6 小时前
Paimon LSM Tree Compaction 策略
java·大数据·数据结构·数据库·算法·lsm-tree
web_Hsir8 小时前
vue3.2 前端动态分页算法
前端·算法
地平线开发者10 小时前
征程 6M 部署 Omnidet 感知模型
算法·自动驾驶
秋说11 小时前
【PTA数据结构 | C语言版】线性表循环右移
c语言·数据结构·算法
浩瀚星辰202411 小时前
图论基础算法:DFS、BFS、并查集与拓扑排序的Java实现
java·算法·深度优先·图论
JiaJZhong13 小时前
力扣.最长回文子串(c++)
java·c++·leetcode
oioihoii13 小时前
C++随机打乱函数:简化源码与原理深度剖析
开发语言·c++·算法
不知名。。。。。。。。14 小时前
分治算法---快排
算法