Skip to content

Commit 21817ba

Browse files
committed
feat: Add Solution to Longest Reapeating Character Replacement #244
- μŠ¬λΌμ΄λ”© μœˆλ„μš°λ₯Ό μ μš©ν•˜μ—¬ λ‹΅μ•ˆμ„ μž‘μ„±ν–ˆμŠ΅λ‹ˆλ‹€.
1 parent 9c6d651 commit 21817ba

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class Solution:
2+
def characterReplacement(self, s: str, k: int) -> int:
3+
"""
4+
Time Complexity: O(n)
5+
Space Complexity: O(1)
6+
"""
7+
n = len(s)
8+
9+
if n == 0:
10+
return 0
11+
12+
left = 0 # μœˆλ„μš°μ˜ μ™Όμͺ½ 인덱슀 (μ‹œμž‘)
13+
max_len = 0 # κ°€μž₯ κΈ΄ μœ νš¨ν•œ λΆ€λΆ„ λ¬Έμžμ—΄ 길이
14+
char_counts = {} # ν˜„ μœˆλ„μš° μ•ˆμ—μ„œ 각 문자 λΉˆλ„μˆ˜
15+
max_freq_count = 0 # ν˜„ μœˆλ„μš° μ•ˆμ—μ„œ κ°€μž₯ 많이 λ“±μž₯ν•œ 문자 λΉˆλ„μˆ˜
16+
17+
for right in range(n):
18+
right_char = s[right] # μœˆλ„μš° 였λ₯Έμͺ½μ— μΆ”κ°€ν•  문자
19+
20+
# μΆ”κ°€ν•  문자 λΉˆλ„μˆ˜ κ°±μ‹ 
21+
char_counts[right_char] = char_counts.get(right_char, 0) + 1
22+
23+
max_freq_count = max(max_freq_count, char_counts[right_char])
24+
25+
current_window_length = right - left + 1
26+
27+
# λ°”κΏ”μ•Ό ν•˜λŠ” 문자 수 = μœˆλ„μš° 길이 - κ°€μž₯ λ§Žμ€ 문자의 λΉˆλ„μˆ˜
28+
changes_needed = current_window_length - max_freq_count
29+
30+
# λ§Œμ•½ λ°”κΏ”μ•Ό ν•˜λŠ” 문자 μˆ˜κ°€ k보닀 크면
31+
# μœ νš¨ν•˜μ§€ μ•Šμ€ μœˆλ„μš° => μœˆλ„μš°λ₯Ό 쀄여야 함
32+
if changes_needed > k:
33+
left_char = s[left] # μ œκ±°ν•  문자
34+
char_counts[left_char] -= 1 # λΉˆλ„μˆ˜ 쀄이기
35+
36+
left += 1 # μœˆλ„μš° μΆ•μ†Œ
37+
38+
# μ΅œλŒ€ 길이 μ—…λ°μ΄νŠΈ, λ°˜ν™˜
39+
max_len = max(max_len, right - left + 1)
40+
41+
return max_len

0 commit comments

Comments
Β (0)