Problem
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.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Sliding Window
This problem is a variant of the problem Longest Substring Without Repeating Characters. We will use a similar sliding-window technique to solve this problem.
Here is the approach:
- Sliding Window Technique:
- Use two pointers (
left
andright
) to represent a sliding window.
- Use two pointers (
- Keep a Frequency Count:
- Use a frequency map or array to track the count of characters in the current window.
- Valid Substring Check:
- Ensure the number of changes required (length of window - frequency of the most common character in the window) does not exceed
k
.
- Ensure the number of changes required (length of window - frequency of the most common character in the window) does not exceed
- Expand and Contract the Window:
- Expand the window by moving
right
. - If the window becomes invalid, move
left
to shrink it.
- Expand the window by moving
- Track the Maximum Length:
- Continuously update the maximum length of a valid window.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the length of the strings
. The sliding window ensures that each character is processed only once. - 🧺 Space complexity:
O(1)
as we only store character frequencies for uppercase English letters (26).