🌗 剑指 Offer 48. 最长不含重复字符的子字符串

吞佛童子2022年10月10日
  • algorithm
  • 滑动窗口
小于 1 分钟

🌗 剑指 Offer 48. 最长不含重复字符的子字符串

难度: 🌗

问题描述

img_10.png


解法

class Solution {
    public int lengthOfLongestSubstring(String s) {
        // 思路:
        // 滑动窗口
        int len = s.length();
        if(len == 0) {
            return 0;
        }
        int left = 0;
        int right = 1;
        HashSet<Character> set = new HashSet<>();
        int res = 1;
        set.add(s.charAt(0));
        while(right < len) {
            char c = s.charAt(right);
            if(!set.contains(c)) {
                res = Math.max(res, right - left + 1);
                right ++;
                set.add(c);
                continue;
            }
            // 遇到重复字符,滑动左窗口
            while(s.charAt(left) != c) {
                char rm = s.charAt(left);
                set.remove(rm);
                left ++;
            }
            left ++;
            res = Math.max(res, right - left + 1);
            right ++;
        }
        return res;
    }
}

输出

img_9.png

上次编辑于: 2022/10/10 下午8:43:48
贡献者: liuxianzhishou