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)。