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;
    }
};
相关推荐
期待のcode6 分钟前
浅堆深堆与支配树
java·jvm·算法
程序员-King.8 分钟前
day156—回溯—组合总和(LeetCode-216)
算法·leetcode·回溯
努力学算法的蒟蒻9 分钟前
day60(1.19)——leetcode面试经典150
算法·leetcode·面试
且去填词11 分钟前
三色标记法与混合写屏障:Go GC 垃圾回收全流程解析
开发语言·算法·golang·三色标记法·gogc·屏障技术
漫随流水12 分钟前
leetcode回溯算法(216.组合总和Ⅲ)
数据结构·算法·leetcode·回溯算法
Leweslyh13 分钟前
【实战】设计一颗“永远向阳”且“姿态稳定”的卫星 (例题 4.8)
算法·航天·轨道力学·星际航行·太阳同步轨道
木木木一16 分钟前
Rust学习记录--C12 实例:写一个命令行程序
学习·算法·rust
大柏怎么被偷了17 分钟前
【C++】哈希桶
数据结构·算法·哈希算法
leaves falling21 分钟前
c语言自定义类型深度解析:联合(Union)与枚举(Enum)
c语言·开发语言·算法
期末考复习中,蓝桥杯都没时间学了38 分钟前
力扣刷题记录2
算法·leetcode·职场和发展