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

84 阅读1分钟

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

1 分析

采用 双指针算法,遍历一次,并且更新最长长度即可

该枚举,是保证所有以 i 为节点的子串

注意 j 的取值是单项的

举例 [j', j, i, i'] 如果 i => i', j如果也可以到j', 那么之前比不可能是 [j,i],至少是[j',i],所以j指针单向

2 Code

function lengthOfLongestSubstring(s: string): number {
  let res = 0;
  const map = new Map();
  for(let i = 0, j = 0; i < s.length; i ++) {
    map.set(s[i], map.has(s[i]) ? map.get(s[i]) + 1 : 1);

    while(map.get(s[i]) > 1) {
      map.set(s[j], map.get(s[j]) - 1);
      j ++;
    }

    res = Math.max(res, i - j + 1);
  }
  return res;
};