Skip to content

Instantly share code, notes, and snippets.

@hasschi
Last active October 18, 2019 06:56
Show Gist options
  • Save hasschi/47339cd5a429a28cb75b6dd2da55906a to your computer and use it in GitHub Desktop.
Save hasschi/47339cd5a429a28cb75b6dd2da55906a to your computer and use it in GitHub Desktop.
LeetCode #3. Longest Substring Without Repeating Characters
/**
* @param {string} s
* @return {number}
*/
var lengthOfLongestSubstring = function(s) {
let result = 0,
str = '';
for(let i = 0; i < s.length; i++){
let c = s[i],
j = str.indexOf(c);//重覆的位置
if(j != -1){
if(str.length > result){
result = str.length;
}
//剩餘長度不足提前結束
if(s.length - 1 - j < result){
break;
}
str = str.substr(j + 1);//重覆字元後面的字串
}
str += c;
}
if(str.length > result){
return str.length;
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment