Skip to content

Commit ecb4679

Browse files
committed
add solution for character replacement problem
1 parent f58e23d commit ecb4679

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
"""
2+
# Approach
3+
1. ๊ตฌ๊ฐ„์—์„œ ์ œ์ผ ๋งŽ์€ ๋ฌธ์ž ์ฐพ๋Š”๋‹ค
4+
2. ๋‚˜๋จธ์ง€๋ฅผ ๋ฐ”๊พผ๋‹ค
5+
3. ๋ฐ”๊พธ๋Š” ๊ฐœ์ˆ˜๊ฐ€ k ์ดํ•˜์ธ์ง€ ๋ณธ๋‹ค
6+
4. ๊ฐ€๋Šฅํ•˜๋ฉด ๊ตฌ๊ฐ„ ๊ธธ์ด๋ฅผ ํ‚ค์šด๋‹ค
7+
8+
# Complexity
9+
๋ฌธ์ž์—ด s์—์„œ ์„œ๋กœ ๋‹ค๋ฅธ ๊ธ€์ž์˜ ์ข…๋ฅ˜ U, s์˜ ๊ธธ์ด N
10+
- Time complexity: O(N)
11+
- Space complexity: O(U) => ์˜์–ด ๋Œ€๋ฌธ์ž๋งŒ ๋‚˜์˜ค๋ฏ€๋กœ ์‚ฌ์‹ค์ƒ O(1)
12+
"""
13+
14+
from collections import defaultdict
15+
16+
17+
class Solution:
18+
def characterReplacement(self, s: str, k: int) -> int:
19+
count = defaultdict(int)
20+
left = 0
21+
max_freq = 0
22+
answer = 0
23+
24+
for right in range(len(s)):
25+
count[s[right]] += 1
26+
max_freq = max(max_freq, count[s[right]])
27+
28+
while (right - left + 1) - max_freq > k:
29+
count[s[left]] -= 1
30+
left += 1
31+
32+
answer = max(answer, right - left + 1)
33+
34+
return answer

0 commit comments

Comments
ย (0)