leetcode/0424_longest-repeating-character-replacement/python3/sliding_window_1.py

43 lines
1.4 KiB
Python

# Time: O(N^2)
# Space: O(N)
from collections import Counter
class Solution:
def characterReplacement(self, s: str, k: int) -> int:
'''
Sliding window approach
'''
def window_size(l, r):
return r - l + 1
# Need to keep track of frequency of each character in the
# window
count = Counter()
l = r = 0
result = 0
while r < len(s):
# Increment the frequency of the `r`th char
count.update(s[r])
# We can perform upto K replacements. So we prefer least num
# of replacements (<= K). In the current window, we can perform
# least replacements for the most common character in the range.
#
# e.g. AAABB K=2, in range 0 to 4, most common char is A, count=3
# so it just needs 5 - 3 = 2 replacements which is <= K which is ok.
#
# But, if K = 1, then we need 5 - 2 = 2 replacements for the same range
# but 2 > K so this window is not valid. We need to move left pointer in
# this case and reduce its count.
if window_size(l, r) - count.most_common(1)[0][1] > k:
count.subtract(s[l])
l += 1
result = max(result, window_size(l, r))
r += 1
return result