Leetcode 424. Longest Repeating Character Replacement
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.
s
comprised only of uppercase English characters?
s
contains only uppercase English alphabet characters.k
be larger or equal to the length of the string s
?
0 <= k <= |s|
where |s|
is the length of the string.s
is an empty string, the function should return 0
.To solve this problem, we can use a sliding window approach to keep track of the substring that has the majority of its characters being the same.
left
to right
) to encompass the current substring.window length - count of majority character
) exceeds k
, then shrink the window from the left.#include <iostream>
#include <string>
#include <unordered_map>
#include <algorithm>
int characterReplacement(const std::string& s, int k) {
int left = 0;
int maxCount = 0; // max count of a single character in the current window
int maxLength = 0;
std::unordered_map<char, int> charCount;
for (int right = 0; right < s.size(); ++right) {
charCount[s[right]]++;
maxCount = std::max(maxCount, charCount[s[right]]);
// If condition fails, we move the left pointer to make it valid
while ((right - left + 1) - maxCount > k) {
charCount[s[left]]--;
left++;
}
maxLength = std::max(maxLength, right - left + 1);
}
return maxLength;
}
int main() {
std::string s = "AABABBA";
int k = 1;
int result = characterReplacement(s, k);
std::cout << "The length of the longest substring after " << k << " replacements is: " << result << std::endl;
return 0;
}
O(N)
where N
is the length of the string s
. Each character is processed at most twice, once when the right
pointer enters the window and once when the left
pointer leaves the window.O(1)
. Although we use an unordered_map, the space complexity will be constant because there are only 26 uppercase English letters.This approach ensures that we efficiently find the longest substring that can be formed by replacing at most k
characters.
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?