java
class Solution {
public int lengthOfLongestSubstring(String s) {
Set<Character> occ = new HashSet<Character>();
int n = s.length();
int rk = -1;
int ans = 0;
for(int i = 0; i < n ; i ++){
// i 往前挪了一格(左边界右移),就要把窗口左边被抛弃的字符删掉
// i-1 就是上一轮窗口最左边的字符,现在它离开窗口了
if (i != 0){occ.remove(s.charAt(i-1));}
while(rk + 1 < n && !occ.contains(s.charAt(rk + 1))){
occ.add(s.charAt(rk + 1));
rk ++;
}
ans = Math.max(ans,rk + 1 - i);
}
return ans;
}
}
注释部分疑问:为啥不直接在每一轮for循环直接new一个hashset
如果每一轮 for(i) 都 new HashSet(),逻辑能跑对,但是时间直接退化到 O (n²),很慢,遇到长字符串会超时;而原题代码复用同一个 set,做到 O (n)。