LeetCode[3].无重复字符的最长子串


CodeBlock Loading...
右指针右移过程中,若有重复一定是第一次重复,因为每次重复都会移出Set。
一定是先移出,再添加;若先添加元素到Set集合,有重复的时候会把刚添加的元素移出。
枚举以右指针r为结尾的无重复的最长子串,在r之前为结尾的无重复字符的子串一定是r为结尾的子串的子集(除非有重复)。
Java代码
class Solution {
public int lengthOfLongestSubstring(String s) {
Set<Character> set = new HashSet<>();
int l = 0,ans = 0;
for(int r = 0;r<s.length();r++){
while(set.contains(s.charAt(r))){
set.remove(s.charAt(l++));
}
set.add(s.charAt(r));
ans = Math.max(r-l+1,ans);
}
return ans;
}
}附上力扣官方题解