封面

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

写作时间:2026-05-02 14:57
# 力扣算法专题
# 滑动窗口

3090. 每个字符最多出现两次的最长子字符串 - 力扣(LeetCode)

条件约束为:

  • 子字符串中每个字符最多出现两次

思路:

  • 用 count 数组记录每个字符出现的次数
  • 当 count[in] 的数超过 2 时,从左边依次出
class Solution {
    public int maximumLengthSubstring(String S) {
        int l=0,r=0;
        int res=0;
        int[] count = new int[26];
        char[] s=S.toCharArray();
        while(r<s.length){
            //进入
            int in=s[r++]-'a';
            count[in]++;
            while(count[in]>2){
                //出
                count[s[l]-'a']--;
                l++;
            }
            //结果
            res=Math.max(res,r-l);
        }
        return res;
    }
}