424. Longest Repeating Character Replacement
Description
See: https://leetcode.com/problems/longest-repeating-character-replacement/
Note that the input string must contain at least one character.
Notes
I read the question wrong, and made it harder than it needed to be. I thought you could only pick one character to replace with another character. For example, could only replace B's with A's. But this is not the case. You could replace multiple letters with the chosen letter.
Example: s = "ABCA" k = 2. Answer 4 because B and C could be replaced with A's. The solution would be "AAAA" which is 4 characters long.
For the solution, we don't actually need to know which letters were replaced. We just need to find the max possible substring.
Solution
A sliding window is used to keep track of the longest substring. As the right pointer increments, we need to check if k
has been exceeded. k
is the number of characters we can change (although we could change less than k
). By keeping track of the letter frequency in the sliding window we can determine if the left pointer needs to increment (and hence decrement the frequency for the letter that is leaving the window).
Last updated