424. Longest Repeating Character Replacement
Medium
Problem:
Input: s = "AABABBA", k = 1
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.Solution:
class Solution:
def characterReplacement(self, s: str, k: int) -> int:
max_len = 0
counts = collections.Counter() # Keeps track of the count of each character in the window
left = right = 0
for right in range(1, len(s) + 1):
counts[s[right - 1]] += 1
# Find the count of the most frequent character in the current window
max_char_n = counts.most_common(1)[0][1]
# If the window size minus the count of the most frequent character is greater than k
# it means we need more than k replacements, so we need to shrink the window
if (right - left) - max_char_n > k:
counts[s[left]] -= 1
left += 1
return right - leftLast updated