LeetCode每日一题(424. Longest Repeating Character Replacement)

该博客探讨了LeetCode中的第424题,即如何在最多进行k次字符替换的情况下,找到字符串中最长的含有相同字母的子串。博主通过滑动窗口策略解释了解决方案,当遇到不同字符时,如果k大于0则用一个'wildcard'替换,若k等于0则移除左侧字符,直至找到'wildcard'或窗口清空,以便右侧继续扩展。最终目标是记录窗口的最大长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.

Return the length of the longest substring containing the same letter you can get after performing the above operations.

Example 1:

Input: s = “ABAB”, k = 2
Output: 4

Explanation: Replace the two 'A’s with two 'B’s or vice versa.

Example 2:

Input: s = “AABABBA”, k = 1
Output: 4

Explanation: Replace the one ‘A’ in the middle with ‘B’ and form “AABBBBA”.
The substring “BBBB” has the longest repeating letters, which is 4.

Constraints:

  • 1 <= s.length <= 105
  • s consists of only uppercase English letters.
  • 0 <= k <= s.length

  1. 26 个大写字母, 针对每个字母遍历一次取最大值
  2. 用 sliding window 的方式, window 内是相同的字符, window 右侧尽可能向右扩展, 遇到与当前字符不相同的字符时如果 k > 0 则放入 wildcard, 如果 k == 0 则重复移除 window 左侧的字符,直到遇到 wildcard 或者 window 变为空, 右侧才可以继续向右扩展. 整个过程中记录 window 的最大长度


impl Solution {
   
   
    fn slide_window(s: &String, mut k: i32, c: char
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值