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

发布于:2022-11-28 ⋅ 阅读:(512) ⋅ 点赞:(0)

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) -> i32 {
        let mut ans = 0;
        let mut curr = 0;
        let mut queue = Vec::new();
        'outer: for char in s.chars() {
            if char != c {
                if k > 0 {
                    k -= 1;
                    queue.push('-');
                    curr += 1;
                    ans = ans.max(curr);
                    continue;
                }
                while !queue.is_empty() {
                    let head = queue.remove(0);
                    curr -= 1;
                    if head == '-' {
                        queue.push('-');
                        curr += 1;
                        ans = ans.max(curr);
                        continue 'outer;
                    }
                }
                continue 'outer;
            }
            queue.push(char);
            curr += 1;
            ans = ans.max(curr);
        }
        ans
    }
    pub fn character_replacement(s: String, k: i32) -> i32 {
        let mut ans = 0;
        for i in 0..26u8 {
            ans = ans.max(Solution::slide_window(&s, k, (i + 65) as char));
        }
        ans
    }
}
本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到