Skip to content

3090. 每个字符最多出现两次的最长子字符串

题目链接:https://leetcode.cn/problems/maximum-length-substring-with-two-occurrences/

代码

ts
/**
 * 3090. 每个字符最多出现两次的最长子字符串
 * https://leetcode.cn/problems/maximum-length-substring-with-two-occurrences/
 */

function maximumLengthSubstring(s: string): number {
    let left = 0;
    let res = 0;
    const map = new Map<string, number>();
    for (let i = 0; i < s.length; i++) {
        const si = s[i];
        map.set(si, (map.get(si) || 0) + 1);
        while (map.get(si)! > 2) {
            map.set(s[left], map.get(s[left])! - 1);
            left++;
        }
        res = Math.max(res, i - left + 1);
    }
    return res;
}

思路

  • 使用滑动窗口 + 计数数组或哈希表,统计当前窗口内每个字符出现次数。
  • 右指针进入窗口时,若某字符出现次数超过 2,则不断移动左指针缩小窗口,直到该字符次数不超过 2。
  • 在这个过程中维护窗口长度的最大值。
  • 时间复杂度 O(n),空间复杂度取决于字符集大小。