Skip to content

Commit 6dcc211

Browse files
committed
- Longest Repeating Character Replacement DaleStudy#244
1 parent c366a00 commit 6dcc211

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution:
2+
"""
3+
- Time Complexity: O(n), n = len(s)
4+
- Space Complexity: O(1)
5+
"""
6+
def characterReplacement(self, s: str, k: int) -> int:
7+
cnt_arr = [0] * 26
8+
max_cnt, max_len = 0, 0
9+
10+
# Two pointers: left/right
11+
l = 0
12+
for r in range(len(s)):
13+
# Increase count and find max count by right pointer's alphabet
14+
idx = ord(s[r]) - ord("A")
15+
cnt_arr[idx] += 1
16+
max_cnt = max(max_cnt, cnt_arr[idx])
17+
18+
# Left pointer moves if changable characters exceed k
19+
if (r - l + 1) - max_cnt > k:
20+
idx = ord(s[l]) - ord("A")
21+
cnt_arr[idx] -= 1
22+
l += 1
23+
24+
# Update the max length
25+
max_len = max(max_len, r - l + 1)
26+
27+
return max_len
28+
29+
tc = [
30+
("ABAB", 2, 4),
31+
("AABABBA", 1, 4)
32+
]
33+
34+
sol = Solution()
35+
for i, (s, k, e) in enumerate(tc, 1):
36+
r = sol.characterReplacement(s, k)
37+
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")

0 commit comments

Comments
 (0)