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 subsequenceand not a substring.
描述:找出字符串最长子序列,返回最长子序列长度。
解法:两个指针i,j 作为滑动窗口。j往后走,将不重复的字符放到HashSet里,这样我们就找到了以i为起始,j为终点的子序列。当遇到重复字符时,删除i所在位置的字符,i向前进一位,遍历完所有的i,即为答案。
public int lengthOfLongestSubstring(String s) { int n = s.length(); int i =0,j=0; int result = 0; HashSet<Character> set = new HashSet<>(); while(i<n&&j<n){ if(!set.contains(s.charAt(j))){ set.add(s.charAt(j)); j++; result = Math.max(result,j-i);//更新最长子序列长度 }else{ set.remove(s.charAt(i)); i++; } } return result; }