> For the complete documentation index, see [llms.txt](https://emmaguo100.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://emmaguo100.gitbook.io/leetcode/03-30-2022-424.-longest-repeating-character-replacement.md).

# 03/30/2022 424. Longest Repeating Character Replacement

Method:

using sliding window. Initiate int count array for capital letters. start from right = 0, get the frequency of the current character, then get the most frequent character number, calculate the current total length by right - left + 1, then we can get the replace*length = current\_totallength - most frequent character length. If the* replace*length > k, then we decrement the frequency of count of left character and increment left index. Otherwise, we get the max value of max and current total length;*

*Time O(n)*

*Space O(1)*

```
// Some code
class Solution {
    public int characterReplacement(String s, int k) {
        int left = 0;
        int length = s.length();
        int maxLength = 0;
        int most_freq = 0;
        int max = Integer.MIN_VALUE;
        
        int[] count = new int[26];
        
        for (int right = 0; right < length; right++){
            char ch = s.charAt(right);
            count[ch - 'A']++;
            maxLength = Math.max(maxLength, count[ch - 'A']);
            int total_current = right - left + 1;
            int rest_length = total_current - maxLength;
            if (rest_length > k){
                count[s.charAt(left) - 'A']--;//REMEMBER
                left++;
            } else {
                max = Math.max(max, total_current);
            }
            
        }
        return max;
    }
}
```
