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

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

Example 1:

Input: s = “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.

Example 2:

Input: s = “bbbbb”
Output: 1
Explanation: The answer is “b”, with the length of 1.

Example 3:

Input: s = “pwwkew”
Output: 3
Explanation: The answer is “wke”, with the length of 3.

思路

滑动窗口

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def lengthOfLongestSubstring(self, s: str) -> int:
chars = set()
length = len(s)

answer, rp = 0, 0
for i in range(length):
if i != 0:
chars.remove(s[i - 1])

while rp < length and s[rp] not in chars:
chars.add(s[rp])
rp += 1

answer = max(answer, rp - i)

return answer

Submissions

Reference 参考

[1] 3. Longest Substring Without Repeating Characters