LeetCode-3. Longest Substring Without Repeating Characters

问题描述

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

Example 1:

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

Constraints:

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

解答

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
/*
* @Description: 3. Longest Substring Without Repeating Characters
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* @param {string} s
* @return {number}
*/
const lengthOfLongestSubstring = function (s) {
const hashTable = {}
let start = -1
let maxLen = 0

for (let end = 0; end < s.length; end++) {
let cur = hashTable[s[end]]
if (cur !== undefined && cur > start) { // 如果遇见重复的字符,且重复的字符在窗口之内
start = cur
}
hashTable[s[end]] = end
maxLen = maxLen > (end - start) ? maxLen : end - start
}
return maxLen
}