Skip to content

Commit f1f82aa

Browse files
committed
feat: add longest repeating character replacement solution
1 parent 857337b commit f1f82aa

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
from collections import defaultdict
2+
3+
4+
class Solution:
5+
def characterReplacement(self, s: str, k: int) -> int:
6+
"""
7+
- Idea: ์Šฌ๋ผ์ด๋”ฉ ์œˆ๋„์šฐ๋ฅผ ์ด์šฉํ•ด ํ˜„์žฌ ์œˆ๋„์šฐ ๋‚ด์—์„œ ๊ฐ€์žฅ ์ž์ฃผ ๋‚˜ํƒ€๋‚˜๋Š” ๋ฌธ์ž์˜ ๊ฐœ์ˆ˜๋ฅผ ์ถ”์ ํ•œ๋‹ค.
8+
์ตœ๋Œ€ k๊ฐœ์˜ ๋ฌธ์ž๋ฅผ ๋ฐ”๊ฟจ์„ ๋•Œ, ๋ชจ๋“  ๋ฌธ์ž๊ฐ€ ๊ฐ™์€ ๋ถ€๋ถ„ ๋ฌธ์ž์—ด์˜ ์ตœ๋Œ€ ๊ธธ์ด๋ฅผ ๊ณ„์‚ฐํ•œ๋‹ค.
9+
์œˆ๋„์šฐ๊ฐ€ ์œ ํšจํ•˜์ง€ ์•Š์œผ๋ฉด, ์™ผ์ชฝ ํฌ์ธํ„ฐ๋ฅผ ์ด๋™์‹œ์ผœ ์œˆ๋„์šฐ ํฌ๊ธฐ๋ฅผ ์กฐ์ •ํ•œ๋‹ค.
10+
- Time Complexity: O(n), n์€ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๋‹ค. ๊ฐ ๋ฌธ์ž๋ฅผ ํ•œ๋ฒˆ์”ฉ ์ˆœํšŒํ•˜๊ณ , ์Šฌ๋ผ์ด๋”ฉ ์œˆ๋„์šฐ๋ฅผ ์กฐ์ •ํ•œ๋‹ค.
11+
- Space Complexity: O(26) = O(1), ์Šฌ๋ผ์ด๋”ฉ ์œˆ๋„์šฐ ๋‚ด์— ํฌํ•จ๋œ ๋ฌธ์ž์˜ ๊ฐœ์ˆ˜๋ฅผ ์„ธ๊ธฐ ์œ„ํ•œ ๊ณต๊ฐ„์œผ๋กœ, ์ตœ๋Œ€ ์•ŒํŒŒ๋ฒณ ๋ฌธ์ž์˜ ๊ฐœ์ˆ˜(26๊ฐœ)๋งŒํผ ๋Š˜์–ด๋‚  ์ˆ˜ ์žˆ๋‹ค.
12+
"""
13+
result = 0
14+
counter = defaultdict(int)
15+
left = 0
16+
17+
for right in range(len(s)):
18+
counter[s[right]] = counter[s[right]] + 1
19+
20+
while (right - left + 1) - max(counter.values()) > k:
21+
counter[s[left]] -= 1
22+
left += 1
23+
24+
result = max(result, right - left + 1)
25+
26+
return result

0 commit comments

Comments
ย (0)