滑动窗口:求字符串中「不含重复字符的最长子串」长度。

思路:维护一个窗口 [left, right],用哈希/集合记录窗口内字符;遇重复就右移 left 直到无重复。

function lengthOfLongestSubstring(s) {
  const set = new Set()
  let left = 0, max = 0
  for (let right = 0; right < s.length; right++) {
    while (set.has(s[right])) {
      set.delete(s[left])
      left++
    }
    set.add(s[right])
    max = Math.max(max, right - left + 1)
  }
  return max
}

同分类其他题目