424. Longest Repeating Character Replacement

424. Longest Repeating Character Replacement

题目描述

Given a string that consists of only uppercase English letters, you can replace any letter in the string with another letter at most k times. Find the length of a longest substring containing all repeating letters you can get after performing the above operations.

Note:
Both the string’s length and k will not exceed 104.

Example 1:

1
2
3
4
5
6
7
8
Input:
s = "ABAB", k = 2
Output:
4
Explanation:
Replace the two 'A's with two 'B's or vice versa.

Example 2:

1
2
3
4
5
6
7
8
9
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.

题目大意

替换字符串 s 中 k 个字符,使字符串拥有最长重复字符。

解题思路

滑动窗口
维护有效区间 l...r,使得区间内除重复字符以外的字符不大于k。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
func characterReplacement(_ s: String, _ k: Int) -> Int {
var dict = Array(repeating: 0, count: 26)
var ans = 0
var l = 0
var chars = Array(s.unicodeScalars)
var maxCount = 0
for (r, char) in chars.enumerated() {
let ascii = Int(char.value) - 65
dict[ascii] += 1
maxCount = max(maxCount, dict[ascii])
while r - l + 1 - dict[Int(chars[l].value) - 65] > k {
dict[Int(chars[l].value) - 65] -= 1
l += 1
}
}
return min(chars.count, maxCount + k)
}
}
0%