题目:Given a string, find the length of the longest substring without repeating characters.
For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
这个题就是快慢指针问题,或者移动窗口? 这类问题每次做还是很小心。主要还是练习少了,并不是很熟练,而且容易搞错。
1 public int lengthOfLongestSubstring(String s) { 2 if (s == null || s.length() == 0) { 3 return 0; 4 } 5 int walker = 0; 6 int runner = 0; 7 int max = 0; 8 HashSet<Character> set = new HashSet<Character>(); 9 while (runner < s.length()) { 10 if (!set.contains(s.charAt(runner))) { 11 set.add(s.charAt(runner)); 12 }else { 13 max = Math.max(max, runner - walker); 14 while (walker < runner && s.charAt(walker) != s.charAt(runner)) { 15 set.remove(s.charAt(walker)); 16 walker++; 17 } 18 walker++; 19 } 20 runner++; 21 } 22 return Math.max(max, runner - walker); 23 }