LeetCode截图

原题

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

解题思路

对题目的理解

  1. 拿到题目看到了最长,首先想到双指针
  2. 字符串可能很长很长(0 <= s.length <= 5 * 104),所以多次遍历比较的方法不可取。
  3. 截取字符串的S1 ~ Sn,判断Sn+1是否在其中,如果在,那当前最长子串是n - 1

show code

function lengthOfLongestSubstring(s: string): number {
  if (s.length < 2) return s.length
  let max = 0
  let startIndex = 0
  const map = new Map<string, number>([])
  const len = s.length
  for (let endIndex = 0; endIndex < len; endIndex++) {
    const cur = s[endIndex]
    if (map.has(cur)) startIndex = Math.max(map.get(cur), startIndex)

    max = Math.max(max, endIndex - startIndex + 1);
    map.set(cur, endIndex + 1)
  }

  return max
}

总结