Easy to understand C++ code, with comments


  • 0
    M

    Same idea as others, but more readable code. Basic idea is to find the maximum substring window, which only contains atmost 'K' different characters from the majority character. That way we can replace those 'K' to be same as majority character.

    '''
    class Solution {
    public:
    int characterReplacement(string s, int k) {

        vector <int> char_count(26);
        
        int left = 0, right = 0, max_same_char = 0, maxlen = 0, diff_chars;
    
        for (int right = 0; right < s.length(); right++) {
            int c = s[right] - 'A';
            
            char_count[c]++;
            
            // Did the max change due to this character ?
            max_same_char = max(max_same_char, char_count[c]);
            
            // Number of different characters
            diff_chars = (right - left + 1) - max_same_char;
            
            // More than our window size ? slide it, decrease the left most
            // character's count
            if (diff_chars > k) {
                char_count[s[left] - 'A']--;
                left++;
            }
            
            // Record the max window that we saw
            maxlen = max(maxlen, (right - left + 1));
        }
        
        return maxlen;
    }
    

    };
    '''


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.