6.滑动窗口-1-无重复字符的最长子串

cloud-yuan
1
2026-06-11
class Solution {
    public int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() == 0) return 0;

        Set<Character> window = new HashSet<>();

        int left = 0;
        int maxLen = 0;

        for(int right=0;right<s.length();right++){

            char c = s.charAt(right);

            while (window.contains(c)) {
                window.remove(s.charAt(left));
                left++;
            }

            window.add(c);
            
            maxLen = Math.max(maxLen, right - left + 1);
        }

        return maxLen;

    }
}

核心思路:

  • 定义窗口:使用左右两个指针 leftright 维护一个子串窗口 [left, right]

  • 扩大窗口right 指针不断向右移动,将新字符加入窗口。

  • 收缩窗口:如果 right 指向的字符在窗口中已经存在,说明出现了重复。此时必须移动 left 指针,直到窗口中不再包含该重复字符为止。

  • 记录极值:在每次窗口合法时(即没有重复字符时),计算当前窗口长度 right - left + 1,并更新全局最大长度。