03. 无重复最长子串
2020-07-11 本文已影响0人
卡尔书院
题目
![](https://img.haomeiwen.com/i10951533/03fe0729dd3f400c.png)
步骤
![](https://img.haomeiwen.com/i10951533/6f635d3514428d0d.png)
正确代码
/**
* @param {string} s
* @return {number}
*/
var lengthOfLongestSubstring = function(s) {
const set = new Set();
let i = 0, j = 0, maxLenth = 0;
for(; i < s.length; i++){
if(!set.has(s[i])){
set.add(s[i]);
maxLenth = Math.max(maxLenth, set.size);
}else{
while(set.has(s[i])){
set.delete(s[j]);
j++;
}
set.add(s[i]);
}
}
return maxLenth;
};
![](https://img.haomeiwen.com/i10951533/32458348480e7ff6.png)
- 我们认为题目中一般不会给出一个空字符串 , 所以省略了以下代码 :
if(s.length === 0){
return 0;
}
错误代码
/**
* @param {string} s
* @return {number}
*/
var lengthOfLongestSubstring = function(s) {
let i, j, maxLenth = 0;
const set = new Set();
if(s.length === 0){
return 0;
}
for(i = 0; i < s.length; i++){
if(!set.has(s[i])){
set.add(s[i]);
maxLenth = Math.max(maxLenth, set.size);
}else{
set.delete(s[j]);
set.add(s[i]);
}
j++;
}
return maxLenth;
};
![](https://img.haomeiwen.com/i10951533/d8e4012c867fae21.png)
- 应循环删除至set中不含有i指针指向的字符为止 , 而不是只删掉一个 ;
如 : i = 3 时 , 需要删除p和w两个字符 . 否则会出现wwke子串 .