Longest Substring Without Duplicates
Given a string s, find the length of the longest substring without duplicate characters.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "zxyzxyz"
Output: 3
Explanation: The string “xyz” is the longest without duplicate characters.
Example 2:
Input: s = "xxxx"
Output: 1
Constraints:
0 <= s.length <= 1000
s may consist of printable ASCII characters.
Solution
A typical sliding window problem, a set can be applied to the statistics of appeared characters, because a character can only appears at most once.
Code
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
le = 0
ans = 0
char_set = set()
for ri in range(len(s)):
while s[ri] in char_set:
char_set.remove(s[le])
le += 1
char_set.add(s[ri])
ans = max(ans, ri-le+1)
return ans