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 subsequenceand not a substring.
/**
* @param {string} s
* @return {number}
*/
var lengthOfLongestSubstring = function(s) {
if(!s){
return 0;
}
var tempObj = {},
resultLen = 1;
for(var left = 0, right = 0; right < s.length; right++){
if(tempObj.hasOwnProperty(s.charAt(right)) && tempObj[s.charAt(right)] >= left){
left = tempObj[s.charAt(right)] + 1;
}
tempLen = right - left + 1;
resultLen = resultLen > tempLen ? resultLen : tempLen;
tempObj[s.charAt(right)] = right;
}
return resultLen;
};