Skip to content

Commit

Permalink
feat: add longest repeating character replacement solution
Browse files Browse the repository at this point in the history
  • Loading branch information
mangodm-web committed Oct 2, 2024
1 parent 857337b commit f1f82aa
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions longest-repeating-character-replacement/mangodm-web.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from collections import defaultdict


class Solution:
def characterReplacement(self, s: str, k: int) -> int:
"""
- Idea: ์Šฌ๋ผ์ด๋”ฉ ์œˆ๋„์šฐ๋ฅผ ์ด์šฉํ•ด ํ˜„์žฌ ์œˆ๋„์šฐ ๋‚ด์—์„œ ๊ฐ€์žฅ ์ž์ฃผ ๋‚˜ํƒ€๋‚˜๋Š” ๋ฌธ์ž์˜ ๊ฐœ์ˆ˜๋ฅผ ์ถ”์ ํ•œ๋‹ค.
์ตœ๋Œ€ k๊ฐœ์˜ ๋ฌธ์ž๋ฅผ ๋ฐ”๊ฟจ์„ ๋•Œ, ๋ชจ๋“  ๋ฌธ์ž๊ฐ€ ๊ฐ™์€ ๋ถ€๋ถ„ ๋ฌธ์ž์—ด์˜ ์ตœ๋Œ€ ๊ธธ์ด๋ฅผ ๊ณ„์‚ฐํ•œ๋‹ค.
์œˆ๋„์šฐ๊ฐ€ ์œ ํšจํ•˜์ง€ ์•Š์œผ๋ฉด, ์™ผ์ชฝ ํฌ์ธํ„ฐ๋ฅผ ์ด๋™์‹œ์ผœ ์œˆ๋„์šฐ ํฌ๊ธฐ๋ฅผ ์กฐ์ •ํ•œ๋‹ค.
- Time Complexity: O(n), n์€ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๋‹ค. ๊ฐ ๋ฌธ์ž๋ฅผ ํ•œ๋ฒˆ์”ฉ ์ˆœํšŒํ•˜๊ณ , ์Šฌ๋ผ์ด๋”ฉ ์œˆ๋„์šฐ๋ฅผ ์กฐ์ •ํ•œ๋‹ค.
- Space Complexity: O(26) = O(1), ์Šฌ๋ผ์ด๋”ฉ ์œˆ๋„์šฐ ๋‚ด์— ํฌํ•จ๋œ ๋ฌธ์ž์˜ ๊ฐœ์ˆ˜๋ฅผ ์„ธ๊ธฐ ์œ„ํ•œ ๊ณต๊ฐ„์œผ๋กœ, ์ตœ๋Œ€ ์•ŒํŒŒ๋ฒณ ๋ฌธ์ž์˜ ๊ฐœ์ˆ˜(26๊ฐœ)๋งŒํผ ๋Š˜์–ด๋‚  ์ˆ˜ ์žˆ๋‹ค.
"""
result = 0
counter = defaultdict(int)
left = 0

for right in range(len(s)):
counter[s[right]] = counter[s[right]] + 1

while (right - left + 1) - max(counter.values()) > k:
counter[s[left]] -= 1
left += 1

result = max(result, right - left + 1)

return result

0 comments on commit f1f82aa

Please sign in to comment.