Skip to content
On this page
js
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3

输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1

输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3
     请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。

思路

  1. 这里用哈希 + 双指针。end++,记录每次字符出现的位置
  2. 如果发现字符在 map 里面,表示当前重复了,那么需要更新 start 指针

代码

js
/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function (s) {
  let start = 0,
    end = 0,
    max = 0,
    map = new Map();

  while (end < s.length) {
    if (map.has(s[end])) {
      // 更新左指针
      // 因为上次 char 的记录 可能未更新,所以判断 l 指针每次都是向前的!
      start = Math.max(start, map.get(s[end]) + 1);
    }
    map.set(s[end], end);
    end++;
    max = Math.max(max, end - start);
  }

  return max;
};

Released under the MIT License.