HZFE / algorithms-solving

1 stars 0 forks source link

2022-09-16 #49

Open github-actions[bot] opened 2 years ago

gongpeione commented 2 years ago

424 Longest Repeating Character Replacement

/*
 * @lc app=leetcode id=424 lang=typescript
 *
 * [424] Longest Repeating Character Replacement
 */

// @lc code=start
function characterReplacement(s: string, k: number): number {
    const counter = {} as { [index: string]: number };
    let ans = 0;
    let left = 0;

    for (let right = 0; right < s.length; right++) {
        // count the letter
        counter[s[right]] = (counter[s[right]] || 0) + 1;

        // if current slide window is not valid (slide window's length minus the max of counter is greater than k)
        // then move the right pointer
        // until the slide window is valid
        while ((right - left + 1) - Math.max(...Object.values(counter)) > k) {
            left++;
            counter[s[left - 1]] -= 1;
        }

        // compare ans and current slide window's length
        ans = Math.max(ans, right - left + 1);
    }

    return ans;
};
// @lc code=end

Nickname: Geeku From vscode-hzfe-algorithms