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.
设置头尾两个指针,当end字符重复时,删除start字符,然后start往右移一个位置。把长度记录下来。
1 public class Solution { 2 public int lengthOfLongestSubstring(String s) { 3 if (s == null || s.length()==0) { 4 return 0; 5 } 6 if (s.length() == 1) { 7 return 1; 8 } 9 int start=0,end=1; 10 int length=1; 11 12 HashSet<Character> set = new HashSet<Character>(); 13 set.add(s.charAt(start)); 14 while (end < s.length()) { 15 if (set.contains(s.charAt(end))) { 16 set.remove(s.charAt(start)); 17 start++; 18 19 20 } else { 21 set.add(s.charAt(end)); 22 length = (end - start + 1) > length ? (end - start + 1) : length; 23 ++end; 24 } 25 26 } 27 28 return length; 29 } 30 }