Leetcode 3 无重复字符的最长子串

题目地址:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/

难度:中等

基本思路:

  • 首先区分子串和子序列,子串是连续的子序列,子序列相当于子集,可以是离散的
  • 使用 sliding window 滑动窗口的概念,想象一下,在字符串中开一个可以左右滑动且能伸缩的窗口
  • 只需要判断当前这个窗口中的字符串是否有重复字符,然后记录每次的没有重复字符的窗口覆盖字符数,取最大值
class Solution {
    // 滑动窗口: 不包含重复字符的滑动窗口, 使用set排除重复元素
    public int lengthOfLongestSubstring(String s) {
        HashSet<Character> hs = new HashSet<Character>();
        int len = s.length();
        int max = 0, tmp;
        int i = 0, j = 0;
        while(i < len){
            if (i != 0) {
                // 左指针向右移动一个字符, 移除前一个字符
                hs.remove(s.charAt(i - 1));
            }
            while(j < len && !hs.contains(s.charAt(j))){
                hs.add(s.charAt(j));
                j++;
            }
            tmp = j - i;
            max = Math.max(max, tmp);
            i++;
        }
        return max;
    }
}
论读书
睁开眼,书在面前
闭上眼,书在心里
原文地址:https://www.cnblogs.com/YC-L/p/14647548.html