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.
思路:
采用兩個變量left和res記錄最長子串的左邊界和最長子串的長度。遍歷字符串,如果沒有在hash表中出現(xiàn)過,就更新長度res,如果出現(xiàn)過就更新左邊界的值。最后給每一位字符串對應(yīng)的位置填入hash表中(從1開始)。注意更新res長度的判斷條件還有一個就是obj[s[i]]<left的值的時候即出現(xiàn)的這個字母即使存在過但他小雨左邊界,也需要更新長度。
var lengthOfLongestSubstring = function(s) {
var obj = {};
var left = 0;
var res = 0;
for (var i = 0; i < s.length; i++) {
if (!obj[s[i]] || obj[s[i]] < left) {
res = Math.max(res, i - left + 1);
} else {
left=obj[s[i]];
}
obj[s[i]] = i + 1;
}
return res
};