Skip to content

无重复字符的最长子串

代码

解法:滑动窗口

1、构建一个数组,遍历字符串 2、若数组中无当前遍历的字符,则将当前字符加入到数组中;若数组中有当前遍历的字符,则删除数组中的该字符及其前面的字符 3、每次遍历时,对比当前maxLen和数组的长度,取大者赋值给maxLen,即maxLen永远保存的是最大长度

js
function getLongestSubstrLen(s) {
  if (s.length === 0) return 0;

  let maxLen = 0;
  let arr = []; // 滑动窗口
  for (let c of s) {
    let index = arr.indexOf(c);
    if (index !== -1) { // 为重复字符,删除该字符及其前面的字符
      arr.splice(0, index+1);
    }
    arr.push(c);
    maxLen = Math.max(maxLen, arr.length);
  }

  return maxLen;
}

MIT Licensed | 沪ICP备20013265号-1 | Copyright © 2019-present AaronKong