
题目:
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be a substring, "pwke"
is a subsequence and not a substring.
代码
var lengthOfLongestSubstring = function(s) {
let result = 0, t = [];//预定义
// var s = 'aab';
var ans = 0, i = 0, j = 0, n= s.length;
while (i < n ) {
// try to extend the range [i, j]
let index = t.indexOf(s[i]);
// if(i==2)
// return index;
if (index < 0){ ans = Math.max(t.push(s[i]),ans);
i++;
}
else {
t= t.slice(index + 1);//返回截取出来的数组
continue;
}
}
return ans; /* O^n */
/*
for (var i = 0; i < s.length; i++) {
//t = t.slice(t.indexOf(s[i]) + 1);//检测是否包含字符串,
let index = t.indexOf(s[i]) + 1;//找到就返回第一次出现的位置 t = t.slice(index);
result = Math.max(t.push(s[i]), result); if(i ==3)
return t;
}
return result
*/
}