Published:
Updated:

  • ํˆฌ ํฌ์ธํ„ฐ์™€ ์Šฌ๋ผ์ด์‹ฑ ์œˆ๋„์šฐ, 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