[리트코드] 424. Longest Repeating Character Replacement

박형진·2023년 1월 1일
0

https://leetcode.com/problems/longest-repeating-character-replacement/description/


1. 코드

class Solution:
    def characterReplacement(self, s: str, k: int) -> int: 
        ans = -1
        d = Counter()
        start = 0
        for end in range(1, len(s)+1):
            d[s[end-1]] += 1
            most = d.most_common(1)[0][1]

            window_length = end-start
            remain = window_length - most

            if remain > k:
                d[s[start]] -= 1
                start += 1

            # 해 구하기
            ans = max(ans, end-start)
        return ans

2. 후기

슬라이딩 윈도우의 크기가 고정된 문제인 438. Find All Anagrams in a String 문제와 다르게, 이 문제는 윈도우의 크기가 동적으로 변할 수 있어서 어렵게 느껴졌다.

# 윈도우의 범위:range(start, end)
# 1부터 시작하여 end-1인덱스를 참조하는 방식 알아둘 것
start = 0
for end in range(1, len(s)+1):
	d[s[end-1]] += 1

end를 for문의 변수로 사용하고 조건문에 따라 start를 이동시키는 방식이다. 슬라이딩 윈도우는 오른쪽으로 한칸씩 움직이는 경우가 대다수이다. 즉 start보다는 end의 이동이 더 빈번하게 발생하므로 end를 for문의 변수로 사용하는 편이 더 쉽게 코드를 짤 수 있다.

start를 for문의 변수로 사용할 경우 한칸씩 움직이는 슬라이딩 윈도우를 구현하려면 for문안에 while문을 사용하여 end를 이동시켜야 한다.

두 방식 모두 생각해놓고 문제에 따라 적합한 방식을 선택하자.

profile
안녕하세요!

0개의 댓글