当前位置: 首页 > 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.dtcms.com/a/163796.html

相关文章:

  • neo4j vs python
  • 小刚说C语言刷题——1032分糖果
  • 【今日三题】小红的ABC(找规律) / 不相邻取数(多状态dp) / 空调遥控(排序+二分/滑动窗口)
  • PLOT: PROMPT LEARNING WITH OPTIMAL TRANSPORT FOR VISION -LANGUAGE MODELS
  • Kafka 的服务端的物理存储架构是什么?零拷贝,mmap,sendfile、DMA gather又是什么?
  • Go语言中的错误处理
  • ETL数据集成与数据资产的紧密关联,解锁数据价值新密码
  • 阿里云服务迁移实战: 04-IP 迁移
  • 阿里云 OpenManus 实战:高效AI协作体系
  • 数据中心网络架构:高效规划与自动化设计实践
  • python的turtle库实现四叶草
  • 缺口拼图,非线性坐标关联
  • Tomcat 部署配置指南
  • Flume启动报错
  • 人工智能数学基础(四):线性代数
  • Plesk 下的 IP 地址管理
  • QT中的网络编程
  • [零基础]内网ubuntu映射到云服务器上,http访问(frp内网穿透)
  • FastDDS 解析xml文件
  • neo4j暴露公网ip接口——给大模型联通知识图谱
  • 【uom】 0 配置文件(Cargo.toml)
  • 【DB2】逻辑导出导入注意事项
  • mongoose的介绍,连接数据库
  • 引力透镜效应添加光线弯曲程度可视化层的MATLAB代码
  • Neo4j 的 `SET n += $properties` 语法详解
  • 2025年04月29日Github流行趋势
  • OpenCV 图形API(72)图像与通道拼接函数-----根据指定的方式翻转图像(GMat)函数 flip()
  • zynq上的裸机lwip网络性能测试iperf使用心得
  • UI-TARS论文解读 并提供镜像
  • Elasticsearch:ES|QL lookup JOIN 介绍 - 8.18/9.0