Loading

力扣 - 3. 无重复字符的最长子串

题目

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

思路(滑动窗口+哈希集合)

  • 使用滑动窗口来解决
  • 首先遍历一遍字符串
  • 使用哈希集合,先判断下一个字符是否存在,如果不存在的话就往set中添加字符,继续判断下一个;如果存在的话,就停止添加,然后向右移动一个窗口
  • 每次窗口向右移动时,窗口中最左边的元素必然会出去,所以需要我们remove

代码

class Solution {
    public int lengthOfLongestSubstring(String s) {
        Set<Character> set = new HashSet<>();
        int res = 0;
        int p = -1;
        int len = s.length();
        for (int i = 0; i < len; i++) {
            // 从第二个开始,每次往后移动一个都要删除一个前面的字符
            if (i != 0) {
                set.remove(s.charAt(i-1));
            }
            // 判断下一个字符是否已经存在,如果存在就结束循环
            while (p + 1 < len && !set.contains(s.charAt(p+1))) {
                // 将不重复的字符添加的集合中
                set.add(s.charAt(p+1));
                // 指针右移
                p++;
            }
            // 获取最长的字串
            res = Math.max(res, set.size());
        }
        return res;
    }
}

复杂度分析

  • 时间复杂度:\(O(N)\),其中 N 为字符串长度
  • 空间复杂度:\(O(∣Σ∣)\),其中 Σ 表示字符集(即字符串中可以出现的字符),∣Σ∣ 表示字符集的大小
posted @ 2020-11-24 23:21  linzeliang  阅读(87)  评论(0)    收藏  举报