You are given a string
Return the length of the longest substring containing the same letter you can get after performing the above operations.
Output: 4
Explanation: Replace the two 'A's with two 'B's or vice versa.
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.
There may exists other ways to achieve this answer too.
Constraints:
0 <= s.length <= 105 s consists of only uppercase English letters.0 <= k <= s.length
Contents
Solution 1 - Using sliding window technique, and HashMap to store number of times a character appeared
In this approach, we are going to apply sliding window technique, using two pointers
Implementation steps:
-
First, we will create five variables
left ,right that we will use to adjust the window,longestCount to hold the count, that a character appeared maximum number of times in current window,result to hold the final result, and aHashMap count to track each character and number of times that the character appeared. -
Next, run a
while loop untilright pointer reaches end of array, and do the following:-
Check if the current character exists in the
count map, if it exists increment its count by 1, otherwise add it to thecount map with value as 1. -
After the current character count is added to
count map, check if the current character is the one that appeared more number of times, then updatelongestCount value. -
Next, check if the current window size has at most
k replacements, i.e. after subtractinglongestCount from current window size(right - left +1) - longestCount > k , this tells us that, how many other characters are there in that window that can be replaced with the character that appeared more number of times.
For example if the string is AAABBCD andk =3 , when we are at character 'D', the character that appeared more number of times is'A' = 3 and the left pointer will be at0 and right pointer will be at6 , so within this window6 -0 +1 (+1 is because the array is 0-indexed) which is 7, and if we subtract A's count then the result will be7 - 3 = 4 , now we know that there are more thank elements that need to be replaced, we can now reduce the count of left most indexed character, and also reduce theleft counter. -
Now, the window size has at most
k character replacements, so update theresult by taking the maximum fromresult (current result) and the current windowright -left +1 , and then increment theright pointer to go to the next character.
-
Check if the current character exists in the
-
Finally, return the
result .
Complexity Analysis:
Time complexity: Above code runs in O(n) time where
Space complexity: O(1), since the input can contain only uppercase English letters, so the
Above implementations source code can be found at