当前位置: 首页 > news >正文

leetcode 2516. 每种字符至少取 K 个

题目描述

滑动窗口问题

可以转化为求按照题目要求从两端取走字符后,中间部分的最大长度。中间部分就是一个滑动窗口。

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;}
};
http://www.xdnf.cn/news/204139.html

相关文章:

  • 【网络原理】从零开始深入理解HTTP的报文格式(一)
  • 人工智能数学基础(三):微积分初步
  • 基于tabula对pdf中的excel进行识别并转换成word(三)
  • UE调试相关
  • AI遇见端动态神经网络:Cephalon(联邦学习+多模态编码)认知框架构建
  • 基于SpringAI实现简易聊天对话
  • 学习记录:DAY20
  • 人工智能数学基础(四):线性代数
  • Vue3调度器错误解析,完美解决Unhandled error during execution of scheduler flush.
  • 【C#】.net core6.0无法访问到控制器方法,直接404。由于自己的不仔细,出现个低级错误,这让DeepSeek看出来了,是什么错误呢,来瞧瞧
  • 51c自动驾驶~合集37
  • 【资料分享】全志T536(异构多核ARMCortex-A55+玄铁E907 RISC-V)工业核心板硬件说明书
  • 【MCP Node.js SDK 全栈进阶指南】高级篇(3):MCP 安全体系建设
  • HarmonyOS NEXT 诗词元服务项目开发上架全流程实战(一、项目介绍及实现效果)
  • [Android] GKD v1.10.3
  • 摆动序列(Java)
  • 安卓基础(点击项目)
  • 怎么把Ubuntu系统虚拟环境中启动命令做成系统服务可以后台运行?
  • ArcPy 中的地理处理工具
  • 打印及判断回文数组、打印N阶数组、蛇形矩阵
  • STL 算法库中的 min_element 和 max_element
  • AI日报 - 2025年04月29日
  • JAVA:线程池
  • 弹性盒子布局
  • 嘉黎县传统手工艺传承与发展交流会圆满举行
  • 【LInux网络】网络层IP协议全面解析
  • 亚马逊低价商城战略全解析:跨境卖家突围价格战的7维作战体系
  • 鸿蒙应用开发 知识点 官网快速定位表
  • 鉴权方案与 Sa-Token(元宝胡编乱造中)
  • 【LaTex】8.2 段落格式