(String, Medium) Longest Repeating Character Replacement

송재호·2025년 8월 8일
0

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

뭔가 예전에 풀었던 것 같은데...
어쨋든 보면 딱 떠오르는건 이것도 슬라이딩 윈도우다.

윈도우 크기를 정할 때 k를 어떻게 사용할 것인가?

  • (right - left + 1) 에서 최빈 알파벳 수를 뺀게 k보다 크면 윈도우 땡겨야 함
    즉, 가장 많이 나온 알파벳과 k를 합치면 보완 가능하다는 뜻

이후 length는 최대 길이로 갱신

class Solution {
    public int characterReplacement(String s, int k) {
        
        int left = 0;
        int length = 0;

        int[] cnt = new int[26];
        int maxCount = 0;

        for (int right=0; right<s.length(); right++) {
            char c = s.charAt(right);

            int idx = c - 'A';
            cnt[idx]++;
            maxCount = Math.max(maxCount, cnt[idx]);

            while (k < (right - left + 1) - maxCount) {
                cnt[s.charAt(left) - 'A']--;
                left++;
            }

            length = Math.max(length, right - left + 1);
        }

        return length;
    }
}
profile
식지 않는 감자

0개의 댓글