Skip to content

Commit 53236d2

Browse files
committed
add solution: longest-repeating-character-replacement
1 parent 34a32a3 commit 53236d2

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
'''
2+
# 424. Longest Repeating Character Replacement
3+
4+
use sliding window to find the longest substring with at most k replacements.
5+
6+
## Time and Space Complexity
7+
8+
```
9+
TC: O(n)
10+
SC: O(1)
11+
```
12+
'''
13+
14+
class Solution:
15+
def characterReplacement(self, s: str, k: int) -> int:
16+
freq = [0] * 26 # A~Z, SC: O(1)
17+
left = 0
18+
max_freq = 0
19+
result = 0
20+
21+
for right in range(len(s)): # TC: O(n)
22+
curr_char_index = ord(s[right]) - 65
23+
freq[curr_char_index] += 1
24+
max_freq = max(max_freq, freq[curr_char_index])
25+
26+
if (right - left + 1) - max_freq > k:
27+
freq[ord(s[left]) - 65] -= 1
28+
left += 1
29+
30+
result = max(result, right - left + 1)
31+
32+
return result

0 commit comments

Comments
 (0)