Given a string, find the length of the longest substring without repeating characters.
给定一个字符串,找到最长无重复子串。
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be a substring, "pwke"
is a subsequence and not a substring.
讲一下思路,无重复的子串,要解决的问题是快速确定目前字符是否已经重复,这个问题显而易见用hash,所以用hashset存储已经出现的值。
然后通过滑动窗口,当滑到的值没有重复添加到hashset并计算当前长度是否比之前的最大长度大,如果重复则在hashset中删除前面的数,直到
将与当前值重复的值删除。
1 public int lengthOfLongestSubstring(String s) { 2 if (s == null) { 3 return 0; 4 } 5 HashSet<Character> set = new HashSet<Character>(s.length()); 6 int result = 0; 7 int pre = 0; 8 int last = 0; 9 while (last < s.length()) { 10 if (set.contains(s.charAt(last))) {//如果包含,从前开始删除直到删除与当前 11 set.remove(s.charAt(pre)); //相同的那个值 12 pre++; 13 } else { 14 set.add(s.charAt(last++));//否则添加当前值并滑到下一个值。 15 //因为last自增了,所以last-pre为当前长度 16 result = Math.max(result,last - pre); 17 } 18 } 19 return result; 20 }