File tree 1 file changed +17
-14
lines changed 1 file changed +17
-14
lines changed Original file line number Diff line number Diff line change 1
1
# https://leetcode.com/problems/longest-substring-without-repeating-characters/
2
2
3
+ from typing import Set
4
+
3
5
4
6
class Solution :
5
7
def lengthOfLongestSubstring (self , s : str ) -> int :
6
- max_length = 0
7
- char_set = set ()
8
- left = 0
9
-
10
- # Iterate through the string
8
+ """
9
+ Start by iterating through the entire string. We'll have a left
10
+ and right pointer indicating a substring with the range
11
+ [left, right]. If we encounter new characters, we increment right
12
+ by one and update the maximum length as needed. If we encounter a
13
+ duplicate, we increment left until that is no longer the case.
14
+ """
15
+ max_length : int = 0
16
+ char_seen : Set [str ] = set ()
17
+ left : int = 0
11
18
for right in range (len (s )):
12
- # We have a new unique character
13
- if s [right ] not in char_set :
14
- char_set .add (s [right ])
19
+ if s [right ] not in char_seen :
20
+ char_seen .add (s [right ])
15
21
max_length = max (max_length , right - left + 1 )
16
-
17
- # We have an old character that came up again
18
22
else :
19
- while s [right ] in char_set :
20
- char_set .remove (s [left ])
23
+ while s [right ] in char_seen :
24
+ char_seen .remove (s [left ])
21
25
left += 1
22
- char_set .add (s [right ])
23
-
26
+ char_seen .add (s [right ])
24
27
return max_length
You can’t perform that action at this time.
0 commit comments