示例 1:
输入: s = "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
一开始自己使用暴力,发现有些用例测试不过,时间复杂度还比较高
这题学到了一个新的解题方法——滑动窗口思想
假设s=“pwwkew”
利用左右指针,右指针右移加入窗口内,左指针右移移出窗口。
先判断hashset中是否含有某元素,若无就加入set中,右指针继续右移,重复上述过程;
代码: 时间复杂度为O(n) n为s的长度
class Solution {
public int lengthOfLongestSubstring(String s) {
HashSet<Character> hash=new HashSet<>();
int len=s.length();
int count=0,left=-1; //位于窗口左侧
for(int i=0;i<len;i++) {
if(i!=0)
hash.remove(s.charAt(i-1)); 逐步删去窗口中的数据
while(left+1<len&&!hash.contains(s.charAt(left+1))) { //如果该数不在窗口内
hash.add(s.charAt(left+1)); //就加入窗口
left++;
}
count=Math.max(count, left-i+1); //更新窗口长度
}
return count;
}
}