파이썬 알고리즘 인터뷰 77번(리트코드 424번) Longest Repeating Character Replacement
https://leetcode.com/problems/longest-repeating-character-replacement/
class Solution:
def characterReplacement(self, s: str, k: int) -> int:
if not s:
return 0
result = 0
left = right = 0
char_count = collections.defaultdict(int)
char_max = set()
char_max_count = 0
change = 0
char_sum = 0
while right < len(s):
while change <= k and right < len(s):
char_count[s[right]] += 1
if char_count[s[right]] == char_max_count:
char_max.add(s[right])
elif char_count[s[right]] > char_max_count:
char_max.clear()
char_max.add(s[right])
char_max_count = char_count[s[right]]
change = (right - left + 1) - char_max_count
if change <= k:
result = max(result, right - left + 1)
right += 1
right -= 1
char_count[s[left]] -= 1
if s[left] in char_max:
if len(char_max) == 1:
char_max_count -= 1
else:
char_max.remove(s[left])
left += 1
if left > right:
return result
char_count[s[right]] -= 1
change = (right - left + 1) - char_max_count
return result
right, left 사의 거리에서 가장 많이 나온 문자의 수를 뺀 값이 k가 된다. 는 잘 파악했는데 자꾸 여러 엣지 케이스들을 처리하다가 코드가 너무 복잡해졌다.hard이고 이게 medium인데 이게 더 어려운 것 같다.class Solution:
def characterReplacement(self, s: str, k: int) -> int:
left = right = 0
max_char_n = 0
counts = collections.defaultdict(int)
for right in range(1, len(s) + 1):
counts[s[right - 1]] += 1
max_char_n = max(max_char_n, counts[s[right - 1]])
if right - left - max_char_n > k:
counts[s[left]] -= 1
left += 1
return right - left