题目链接:https://leetcode.com/problems/longest-substring-without-repeating-characters/
解题思路:
1、找到字符串中最长的一个串,并且串里没有相同的字符
2、设置left,right。每判断一个字符,如果没出现在set里,那么就把他放进set里,right++。如果出现了重复的,我就删前面已经的有的这个滑动窗口(直到删到我当前right的指针走到的那个字符的位置后边)
abcabcbb right走到第二个a时,删除第一个a。
abcbbbb right走到第二个b时,left=0,left=1,删掉第一个b,这时set是cb。
原则是始终保持set里没有与当前right走到的位置没有相同的字符为止。
1 public class Solution { 2 public int lengthOfLongestSubstring(String s) { 3 int res = 0, left = 0, right = 0; 4 HashSet<Character> t = new HashSet<Character>(); 5 while (right < s.length()) { 6 if (!t.contains(s.charAt(right))) { 7 t.add(s.charAt(right)); 8 right++; 9 res = Math.max(res, t.size()); 10 } else { 11 t.remove(s.charAt(left)); 12 left++; 13 } 14 } 15 return res; 16 } 17 }