Skip to content

Commit 887b8d9

Browse files
committed
solve(w08): 424. Longest Repeating Character Replacement
1 parent aa1d93e commit 887b8d9

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# https://leetcode.com/problems/longest-repeating-character-replacement/
2+
3+
class Solution:
4+
def characterReplacement(self, s: str, k: int) -> int:
5+
"""
6+
[Complexity]
7+
- TC: O(n)
8+
- SC: O(n)
9+
10+
[Approach]
11+
two pointer๋กœ sliding window๋ฅผ ์ด๋™ํ•ด๊ฐ€๋ฉด์„œ, k๋ฒˆ ์ด๋‚ด๋กœ replace ํ–ˆ์„ ๋•Œ ๋ชจ๋‘ ๊ฐ™์€ ๋ฌธ์ž๊ฐ€ ๋  ๋•Œ์˜ max_len๋ฅผ ํŠธ๋ž˜ํ‚นํ•˜๋ฉด ๋œ๋‹ค.
12+
์ด๋•Œ, ์ด substring์„ ๋ชจ๋‘ ๊ฐ™์€ ๋ฌธ์ž๋กœ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ๊ฐ€์žฅ ์ž‘์€ replacement ํšŸ์ˆ˜๋ฅผ ๊ตฌํ•ด k์™€ ๋น„๊ตํ•ด์•ผ ํ•˜๋Š”๋ฐ,
13+
์ด ํšŸ์ˆ˜ max_replace๋Š” (substring์˜ ๊ธธ์ด - ๊ฐ€์žฅ ๋นˆ๋„๊ฐ€ ๋†’์€ ๋ฌธ์ž์˜ ๋“ฑ์žฅ ํšŸ์ˆ˜) ์ด๋‹ค.
14+
max_replace๊ฐ€ k ์ดํ•˜๋ผ๋ฉด max_len์„ ์—…๋ฐ์ดํŠธํ•˜๊ณ , ์•„๋‹ˆ๋ผ๋ฉด left๋ฅผ ํ•œ ์นธ ์ „์ง„ํ•œ๋‹ค.
15+
"""
16+
from collections import defaultdict
17+
18+
left = max_len = max_freq = 0 # left ~ right: k๋ฒˆ ์ด๋‚ด๋กœ replace ํ–ˆ์„ ๋•Œ, ๋ชจ๋‘ ๊ฐ™์€ ๋ฌธ์ž์ผ ๋•Œ์˜ max_len ์—…๋ฐ์ดํŠธ
19+
cnt = defaultdict(int) # left ~ right sliding window ๋‚ด์—์„œ์˜ counter
20+
21+
# right ํ•œ ์นธ์”ฉ ์ด๋™ํ•ด๊ฐ€๋ฉฐ ํ™•์ธ
22+
for right in range(len(s)):
23+
# max_freq ์—…๋ฐ์ดํŠธ
24+
cnt[s[right]] += 1
25+
max_freq = max(max_freq, cnt[s[right]])
26+
27+
# ํ˜„์žฌ sliding window๋ฅผ ๋ชจ๋‘ ๊ฐ™์€ ๋ฌธ์ž๋กœ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ๊ฐ€์žฅ ์ž‘์€ replacement ํšŸ์ˆ˜ ๊ตฌํ•˜๊ธฐ
28+
sub_len = right - left + 1
29+
min_replace = sub_len - max_freq
30+
31+
# min_replace๊ฐ€ k ์ดํ•˜์ด๋ฉด, max_len ์—…๋ฐ์ดํŠธ
32+
if min_replace <= k:
33+
max_len = max(max_len, sub_len)
34+
# ์•„๋‹ˆ๋ผ๋ฉด, left ํ•œ ์นธ ์ด๋™
35+
else:
36+
cnt[s[left]] -= 1
37+
left += 1
38+
39+
return max_len

0 commit comments

Comments
ย (0)