中等 | 滑动窗口 |

一. 题目描述

给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。

二. 题目示例

:::tips 输入:s = “abcabcbb”
输出:3
::: :::tips 输入:s = “bbbbb”
输出:1
::: :::tips 输入:s = “pwwkew”
输出:3
:::

三. 题目解答

1. 思路

设置头指针、尾指针,记录字符和所在下标的数据结构。固定头指针,尾指针后移,对当前遍历到的尾指针所在元素做判断:
如果重复,移动头指针位置,删除当前重复字符的记录;
插入新的记录,并比较当前长度与最大长度。
最后返回最大长度。

2. 代码

  1. var lengthOfLongestSubstring = function(s) {
  2. let result = 0;
  3. let i=0;
  4. let temp = [];
  5. while(i < s.length){
  6. const index = temp.indexOf(s[i]);
  7. if(index !== -1){
  8. temp = temp.splice(index+1);
  9. }
  10. temp.push(s[i]);
  11. result = Math.max(result, temp.length);
  12. i++;
  13. }
  14. return result;
  15. };