我的js算法爬坑之旅-无重复字符的最长子串

124 阅读1分钟

第五十九天:力扣3题,无重复字符的最长子串

地址:leetcode-cn.com/problems/lo…

思路:滑动窗口

在js中我们使用一个数组来维护滑动窗口,遍历字符串,判断字符串是否在滑动窗口数组里面 不在则push进数组 在则删除滑动窗口数组里相同字符以及相同字符前的字符,然后将当前字符push进数组然后将max更新为当前最长子串的长度遍历完成,返回max即可。

var lengthOfLongestSubstring = function(s) {
  let c = s.split('');
  let res = [];
  let max = 0;
  for(let i = 0; i < c.length; i++)
  {
    if(res.indexOf(c[i]) !== -1)
    {
      res.splice(0, res.indexOf(c[i]) + 1);
    }
    res.push(c[i]);
    max = Math.max(res.length, max);
  }
  return max;
};

执行用时:124 ms, 在所有 JavaScript 提交中击败了47.19%的用户

内存消耗:42 MB, 在所有 JavaScript 提交中击败了58.41%的用户