leetcode第三题lengthOfLongestSubstring
LeeSir 发表于 2015年10月30日 17:21

https://leetcode.com/problems/longest-substring-without-repeating-characters/

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {
    s = s.split(');
    var temp = {};
    var result = 0;
    var count = 0;
    var start = 0;
    for (var i = 0, len = s.length; i < len; i ++) {
        if (temp[s[i]] === undefined || temp[s[i]] < start) {
            temp[s[i]] = i;
            count ++;
        } else {
            result = Math.max(count, result);
            count = i - temp[s[i]];
            start = temp[s[i]] + 1;
            temp[s[i]] = i;
        }
    }
    return Math.max(count, result);
};