算法思路:此处认为只有小写的 a-z 26个英文字母。exists数组保存当前字母是否出现过,position数组记录出现过的字符串的字母的位置。
分为两种情况 1.字母出现过,此时根据position数组把出现过的字母重新置为exists不存在,start指向该出现过的字母的下一个位置,即start+1,end+1.
2.字母没出现过,end+1,修改标志数组对应下标,并记录出现的位置。
/**
* @param {string} s
* @return {number}
*/
var lengthOfLongestSubstring = function(s) {
var max = 0,
start = 0,
exists = [],
position = []; //当然走到的位置
//初始化数组
for(var i = 0; i < 26 ; i++){
exists[i] = false;
position[i] = 0;
}
var a_int = 'a'.charCodeAt();
for(var end = 0; end < s.length ; end++ ){
if(exists[s[end].charCodeAt()-a_int] ){
for(var j = start; j <= position[s[end].charCodeAt() - a_int]; j++) {
exists[s[j].charCodeAt()-a_int] = false;
}
start = position[s[end].charCodeAt() - a_int] + 1;
exists[s[end].charCodeAt()-a_int] = true;
position[s[end].charCodeAt() - a_int] = end;
}
else{
exists[s[end].charCodeAt()-a_int] = true;
position[s[end].charCodeAt() - a_int] = end;
//更新最大长度
max = max > (end - start + 1) ? max : (end - start + 1);
}
}
return max;
};