Skip to content

Commit 3495323

Browse files
committed
feat: [Week 08-2] solve longest repeating character replacement
1 parent 175a780 commit 3495323

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
"""
2+
Solution:
3+
1) sliding window ํ™œ์šฉ
4+
2) window ์— ๋“ค์–ด๊ฐ€๋Š” ๊ธ€์ž๋“ค์€ counts ๋ผ๋Š” hash map ์œผ๋กœ ๊ฐฏ์ˆ˜๋ฅผ ์„ธ์–ด์ค€๋‹ค.
5+
3) ์ˆœํšŒ๋ฅผ ํ•˜๋ฉด์„œ window size ๊ฐ€ counts์—์„œ ๊ฐ€์žฅ ํฐ์ˆซ์ž + k ๋ณด๋‹ค ํฌ๋ฉด invalid window ์ด๊ธฐ์— left ๊ธ€์ž ๊ฐฏ์ˆ˜๋ฅผ ๋นผ๊ณ  ํฌ์ธํ„ฐ๋ฅผ ์ด๋™ํ•ด์ค€๋‹ค.
6+
4) max_count ๋Š” ๊ธฐ์กด max ๊ฐ’๊ณผ ํ˜„์žฌ window ์‚ฌ์ด์ฆˆ ์ค‘ ํฐ ์ˆซ์ž๋ฅผ ์…‹ํ•ด์ค€๋‹ค.
7+
8+
Time: O(n) = O(26n)
9+
Space: O(1) = O(26)
10+
"""
11+
12+
13+
class Solution:
14+
def characterReplacement(self, s: str, k: int) -> int:
15+
counts = defaultdict(int)
16+
max_count = 0
17+
18+
l, r = 0, 0
19+
while l <= r and r < len(s):
20+
counts[s[r]] += 1
21+
window_size = r - l + 1
22+
23+
if window_size > max(counts.values()) + k:
24+
counts[s[l]] -= 1
25+
l += 1
26+
27+
window_size = r - l + 1
28+
max_count = max(window_size, max_count)
29+
r += 1
30+
31+
return max_count

0 commit comments

Comments
ย (0)