Open lancui1110 opened 7 years ago
/**
* @param {string} s
* @return {number}
*/
var lengthOfLongestSubstring = function(s) {
if (s.length === 0) return 0
var res = {}, len = 0
for (var i=0, j=0; i < s.length; i++) {
var w = s.charAt(i), resw = res[w]
if (resw !== undefined) {
j = Math.max(j, resw + 1)
}
res[w] = i
len = Math.max(len, i - j + 1)
}
return len
};
/ 思路:创建一个数组用于存放不重复的字符串,遍历,没有重复则Push进数组;重复了,则记录重复的索 引,删除重复的索引之前的元素重新开始push, 同时一直保持记录数组的最大长度 / var lengthOfLongestSubstring = function(s) { var maxLength = 0, // substr = []; //存放不重复子串 for (var i = 0, l = s.length; i<l; i++){ var repeatIndex = substr.indexOf(s[i]); if (repeatIndex === -1){//没有重复 substr.push(s[i]); maxLength = Math.max(substr.length, maxLength) } else{//重复 substr = substr.slice(repeatIndex+1); substr.push(s[i]); maxLength = Math.max(substr.length, maxLength) } } return maxLength; };
Given a string, find the length of the longest substring without repeating characters.
Examples: