3\. Longest Substring Without Repeating Characters

# 3. Longest Substring Without Repeating Characters (opens new window)

# Description

Difficulty: Medium

Related Topics: Hash Table (opens new window), String (opens new window), Sliding Window (opens new window)

Given a string s, find the length of the longest substring without repeating characters.

Example 1:

Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
1
2
3

Example 2:

Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
1
2
3

Example 3:

Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
1
2
3
4

Constraints:

  • 0 <= s.length <= 5 * 104
  • s consists of English letters, digits, symbols and spaces.

# Solution

Language: JavaScript

/**
 * @param {string} s
 * @return {number}
 方法一:暴力求解
 逐个生成子字符串
 看它是否不含有重复的字符
 
 方法二:滑动窗口及优化
 关键字:重复字符 -> 出现1次
 模式识别1:一旦涉及出现次数,需要用到散列表
 构造子串,散列表下标
 模式识别2:涉及子串,考虑滑动窗口
 
 举例分析思路
 p w w k e w
 
 测试:
 字符串为空的情况
 字符串均为重复字符的情况
 测试其他常规输入
 
 */
var lengthOfLongestSubstring = function(s) {
    const set = new Set();
    let [start, end, maxLen] = [0, 0, 0];
    
    while(end < s.length) {
        set.has(s[end]) ? set.delete(s[start++]) : set.add(s[end++]);
        
        maxLen = Math.max(maxLen, set.size);
    }
    
    return maxLen;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
上次更新: 2022/7/13 上午11:21:17