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:固定一个字符,记录由它开头的不重复的字符串的最大长度。复杂度
O(n2)
,结果超时。
思路2:借鉴http://www.aichengxu.com/view/11060的方法,我们利用双指针的思想(l和r,初始都指向0),r向右移动,直到重复元素出现,记录此时的长度与全局长度比较并更新,然后移动l,直到它所指的元素是这个重复元素的下一个,这期间的元素不用考虑。
代码如下:
public int lengthOfLongestSubstring(String s) {
if(s.length() == 0)
return 0;
int begin = 0;
int end = 0;
int maxlength = 1;
HashSet<Character> h = new HashSet<Character>();
while(end < s.length())
{
if(h.contains(s.charAt(end)))
{
if(maxlength<end-begin)
maxlength = end-begin;
while(s.charAt(begin) != s.charAt(end))
{
h.remove(s.charAt(begin));
begin++;
}
begin++;
}
else
{
h.add(s.charAt(end));
}
end++;
}
maxlength = Math.max(maxlength,end-begin);
return maxlength;
}