给定一个字符串
s
,请你找出其中不含有重复字符的 最长子串 的长度。示例 1:
输入: s = "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
思路:滑动窗口
存储窗口中的字符以检验字符是否出现过:HashSet
窗口左指针:n
窗口右指针:r
左指针没滑动一次就移出最左边的字符,并持续移动右指针直到右指针下一个字符出现过
class Solution {
public int lengthOfLongestSubstring(String s) {
Set<Character> ooc=new HashSet<Character>();
// Set<Character> occ = new HashSet<Character>();
int r=-1;
int res=0;
for(int n=0;n<s.length();n++){
if(n!=0){
ooc.remove(s.charAt(n-1));
}
while(r+1<s.length() && !ooc.contains(s.charAt(r+1))){
ooc.add(s.charAt(r+1));
r++;
}
res=Math.max(res,r-n+1);
}
return res;
}
}