You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.

Return the length of the longest substring containing the same letter you can get after performing the above operations.

 

解题思路:

- use a HashMap to count the frequency of each letter. 使用HashMap记录每个字符出现的频率。

- iterate through the string to add one letter at a time in the window. 遍历字符串,每次向窗口(HashMap)中添加一个新的字符。

-  keep track of the count of the maximum repeating letter in any window maxRepeatLetterCount. 记录每个窗口中重复字符的最大值 maxRepeatLetterCount,

- So at any time, we know that we can have a window which has one letter repeating maxRepeatLetterCount times, this means we should try to replace the remaining letters. If we have more than ‘k’ remaining letters, we should shrink the window as we are not allowed to replace more than ‘k’ letters. 当某个窗口含有 maxRepeatLetterCount 值,应当尝试替换其中所有剩余字符。如果剩余字符超过k,缩减窗口。

 

 

复制代码
class Solution {
    public int characterReplacement(String s, int k) {
        int start = 0, end = 0, maxFrequency = Integer.MIN_VALUE;
        HashMap<Character, Integer> hashMap = new HashMap<>();
        int maxLength = 0;
        //iterate the string and extend window range from the right side
        for (end = 0; end < s.length(); end++){
            char rightChar = s.charAt(end);
            hashMap.put(rightChar, hashMap.getOrDefault(rightChar, 0) + 1);
            maxFrequency = Math.max(hashMap.get(rightChar), maxFrequency);
            
            //shrink the window from the left
            if(end - start + 1 - maxFrequency > k){
                char leftChar = s.charAt(start);
                hashMap.put(leftChar, hashMap.get(leftChar) - 1);
                start++;
            }
            
        }
        maxLength = end - start;
        return end - start;
    }
}
复制代码

 

Time Complexity : O(N) - 遍历一轮

Space Complexity: O(26) - 字母总个数

posted on 2022-04-07 17:38  黎酒  阅读(29)  评论(0)    收藏  举报