Longest Repeating Character Replacement LeetCode solution in Python

1
class Solution:
2
def characterReplacement(self, s: str, k: int) -> int:
3
# Initialize variables
4
window_start = 0
5
max_length = 0
6
max_count = 0
7
char_count = {}
8

9
# Traverse the string s
10
for window_end in range(len(s)):
11
# Increment the count of the current character
12
char_count[s[window_end]] = char_count.get(s[window_end], 0) + 1
13
# Update the maximum count seen so far
14
max_count = max(max_count, char_count[s[window_end]])
15

16
# Shrink the window if required
17
if window_end - window_start + 1 > max_count + k:
18
char_count[s[window_start]] -= 1
19
window_start += 1
20

21
# Update the maximum length of the substring with repeating characters seen so far
22
max_length = max(max_length, window_end - window_start + 1)
23

24
return max_length

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0