zoukankan      html  css  js  c++  java
  • LeetCode: 3 无重复字符的最长子串 (Java)

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

    https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/ 

    最初始的解法方法就是遍历暴力每个元素,然后以那个元素为起始点,然后进行判断是否出现了重复元素,这样时间的复杂度就是O(n2),这样的时间复杂度有点高,基本上已经预定了时间超出限制。所以我们要用别的解法方法。 
    那么比较好的解决方法就是用 双指针的思想,这题其实把握了思想还是挺简单的,要保证无重复的的,一般会先想到HashSet,可以保证数组的字符的唯一性。 
    设置一左一右两个指针,每次我们都移动右指针,如果右边的指针中的元素在Set中存在了,那么就要开始根据已经存在的元素移动左边指针了。同时我们要把左右指针里面的元素所在的索引值(index)给保存下来。 
    代码还是很好理解的:

    show the code

     1 public int lengthOfLongestSubstring(String s) {
     2     if (s.length() == 0) return 0;
     3     Set<Character> set = new HashSet<>();
     4     LinkedList<Integer> list = new LinkedList<>();
     5     char[] charsArray = s.toCharArray();
     6     int left = 0;
     7     int res = 0;
     8     for (int right = 0, len = charsArray.length; right < len; ++right) {
     9         if (set.contains(charsArray[right])) {
    10             res = Math.max(res, right - left);
    11             while (set.contains(charsArray[right])) {
    12                 int index = list.removeFirst();
    13                 set.remove(charsArray[index]);
    14             }
    15             list.addLast(right);
    16             left = list.getFirst();
    17             set.add(charsArray[right]);
    18         } else if (right == len - 1) {
    19             res = Math.max(res, right - left + 1);
    20         } else {
    21             set.add(charsArray[right]);
    22             list.addLast(right);
    23         }
    24     }
    25     return res;
    26 }

    时间复杂度O(n),空间复杂度O(n)。

    欢迎关注公众号:DataWatching

    我的微信公众号:DataWatching

  • 相关阅读:
    51nod 1067 Bash游戏 V2
    洛谷 P1454 圣诞夜的极光 == codevs 1293 送给圣诞夜的极光
    bzoj4754: [Jsoi2016]独特的树叶
    bzoj 4241: 历史研究
    bzoj 1266 [AHOI2006] 上学路线
    bzoj4571: [Scoi2016]美味
    bzoj4570: [Scoi2016]妖怪
    51nod 1238 最小公倍数之和 V3
    一个康托展开的板子
    poweroj1745: 餐巾计划问题
  • 原文地址:https://www.cnblogs.com/jamesmarva/p/11260007.html
Copyright © 2011-2022 走看看