Skip to content

Commit 7c854cb

Browse files
committed
week 08 longest-repeating-character-replacement
1 parent dccca12 commit 7c854cb

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution:
2+
def characterReplacement(self, s: str, k: int) -> int:
3+
count = {}
4+
5+
# ๊ฒฐ๊ณผ๋ฅผ ์ €์žฅํ•  ๋ณ€์ˆ˜ (์ตœ๋Œ€ ๊ธธ์ด)
6+
max_length = 0
7+
8+
# ์œˆ๋„์šฐ ์™ผ์ชฝ ํฌ์ธํ„ฐ
9+
left = 0
10+
11+
# ํ˜„์žฌ ์œˆ๋„์šฐ ๋‚ด์—์„œ ๊ฐ€์žฅ ๋งŽ์ด ๋“ฑ์žฅํ•œ ๋ฌธ์ž์˜ ๋นˆ๋„์ˆ˜
12+
max_frequency = 0
13+
14+
# right ํฌ์ธํ„ฐ๋ฅผ 0๋ถ€ํ„ฐ ๋๊นŒ์ง€ ์ด๋™
15+
for right in range(len(s)):
16+
current_char = s[right]
17+
18+
# ํ˜„์žฌ ๋ฌธ์ž์˜ ์นด์šดํŠธ ์ฆ๊ฐ€
19+
count[current_char] = count.get(current_char, 0) + 1
20+
21+
# ํ˜„์žฌ ์œˆ๋„์šฐ ๋‚ด์˜ '์ตœ๋นˆ ๋ฌธ์ž' ๊ฐœ์ˆ˜ ๊ฐฑ์‹ 
22+
# ์ƒˆ๋กœ ๋“ค์–ด์˜จ ๋ฌธ์ž๊ฐ€ ์ตœ๋นˆ ๋ฌธ์ž๊ฐ€ ๋  ์ˆ˜๋„ ์žˆ์œผ๋ฏ€๋กœ ๋น„๊ต
23+
max_frequency = max(max_frequency, count[current_char])
24+
25+
# ์œˆ๋„์šฐ ํฌ๊ธฐ = (right - left + 1)
26+
# ๋‚˜๋จธ์ง€ ๋ฌธ์ž ๊ฐœ์ˆ˜ = ์œˆ๋„์šฐ ํฌ๊ธฐ - ์ตœ๋นˆ ๋ฌธ์ž ๊ฐœ์ˆ˜
27+
window_len = right - left + 1
28+
if (window_len - max_frequency) > k:
29+
# ์™ผ์ชฝ ๋ฌธ์ž๋ฅผ ์œˆ๋„์šฐ์—์„œ ์ œ๊ฑฐ
30+
left_char = s[left]
31+
count[left_char] -= 1
32+
left += 1 # ์™ผ์ชฝ ํฌ์ธํ„ฐ ์ด๋™
33+
max_length = max(max_length, right - left + 1)
34+
35+
return max_length

0 commit comments

Comments
ย (0)