• 투 포인터와 μŠ¬λΌμ΄μ‹± μœˆλ„μš°, Counter 기법 λͺ¨λ‘ μ‚¬μš©ν•΄μ•Ό μ‹œκ°„ μ΄ˆκ³Όκ°€ λ‚˜μ§€ μ•ŠμŒ


Solution

import collections


class Solution:
    def characterReplacement(self, s: str, k: int) -> int:
        answer = 0

        lt, rt = 0, 0
        counter = collections.Counter()

        while rt < len(s):
            counter[s[rt]] += 1
            # ltλΆ€ν„° rtκΉŒμ§€ κ°€μž₯ λ§Žμ€ 문자의 개수
            most_common = counter.most_common(1)[0][1]
            # λ°”κΏ”μ•Ό ν•  문자 수
            remain = rt - lt + 1 - most_common

            # λ°”κΏ”μ•Ό ν•  문자 μˆ˜κ°€ λ°”κΏ€ 수 μžˆλŠ” 문자 μˆ˜λ³΄λ‹€ λ§Žμ„ λ•Œ
            if remain > k:
                counter[s[lt]] -= 1
                # ltλ₯Ό μ¦κ°€μ‹œμΌœ μœˆλ„μš° 수λ₯Ό μ€„μž„
                lt += 1

            answer = max(rt - lt + 1, answer)
            rt += 1

        return answer


Reference

Leave a comment