LeetCode 3. 无重复字符的最长子串

Posted by cody1991 on August 11, 2020

3. 无重复字符的最长子串

下面的方法是简单,但是效率有点低下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function (s) {
  const map = {};
  let max = 0;

  for (let left = 0, right = 0; right < s.length; right += 1) {
    const c = s[right];

    if (map[c] !== undefined) {
      left = Math.max(left, map[c] + 1);
    }

    map[c] = right;
    max = Math.max(max, right - left + 1);

    console.log(max, left, right);
  }

  return max;
};

console.log(lengthOfLongestSubstring('abba'));