Skip to content

Commit 0bf06ac

Browse files
committed
solve: longestRepeatingCharacterReplacement
1 parent 0ad52c0 commit 0bf06ac

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Time Complexity: O(n) - loop through the string once, and operations like `max(count.values())` are constant time because there are at most 26 characters.
2+
# Space Complexity: O(1) - `count` only stores counts for up to 26 characters.
3+
4+
class Solution:
5+
def characterReplacement(self, s: str, k: int) -> int:
6+
# keep track of counts in the current window
7+
count = {}
8+
9+
left, right = 0, 0
10+
res = 0
11+
12+
# move the right pointer across the string
13+
for right in range(len(s)):
14+
# update the count for the character at the right pointer
15+
count[s[right]] = count.get(s[right], 0) + 1
16+
17+
# if the window size minus the most frequent char count is bigger than k,
18+
# need to shrink the window from the left
19+
while (right - left + 1) - max(count.values()) > k:
20+
# reduce the count of the char at the left pointer and move the left pointer
21+
count[s[left]] -= 1
22+
left += 1
23+
24+
# update the max length of the valid window
25+
res = max(res, right - left + 1)
26+
27+
return res

0 commit comments

Comments
 (0)