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.
1 <= s.length <= 10^5
s consists of only uppercase English letters.
0 <= k <= s.length
To solve this problem efficiently, we can use a sliding window approach. This approach helps us to maintain the longest window (substring) that can be converted to a repeating character string by performing at most k
replacements.
left
and right
) to represent the current window in the substring.right
pointer to expand the window and update the frequency count.k
. If valid, update the maximum length found.left
pointer to shrink the window until it becomes valid.left
and right
pointers at the beginning of the string.right
pointer to the right.k
.left
pointer to the right to reduce the window size until it becomes valid.def characterReplacement(s: str, k: int) -> int:
left = 0
max_count = 0 # max frequency of a single character in the current window
counts = {}
max_length = 0
for right in range(len(s)):
counts[s[right]] = counts.get(s[right], 0) + 1
max_count = max(max_count, counts[s[right]])
# if window size minus the count of the most frequent character is greater than k, it's invalid
while (right - left + 1) - max_count > k:
counts[s[left]] -= 1
left += 1
max_length = max(max_length, right - left + 1)
return max_length
This approach efficiently finds the longest substring that meets the criteria using the sliding window technique.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?