File tree Expand file tree Collapse file tree 1 file changed +14
-13
lines changed Expand file tree Collapse file tree 1 file changed +14
-13
lines changed Original file line number Diff line number Diff line change
1
+ import collections
2
+
3
+
1
4
class Solution :
2
5
def lengthOfLongestSubstring (self , s ):
3
6
"""
4
7
:type s: str
5
8
:rtype: int
6
9
"""
7
10
ans = 0
11
+
8
12
if not s :
9
13
return ans
10
14
11
- n = len (s )
12
- F = {} # frequency for every char between `left`, `right`
13
- rep = 0 # contained repeated char between `left`, `right`
15
+ freqs = collections .defaultdict (int )
16
+ i = rep = 0
14
17
15
- left = right = 0
16
- while right < n :
17
- F [s [right ]] = F .get (s [right ], 0 ) + 1
18
- if F [s [right ]] == 2 :
18
+ for j in range (len (s )):
19
+ if freqs [s [j ]] == 1 :
19
20
rep += 1
20
- right += 1
21
+ freqs [ s [ j ]] += 1
21
22
22
23
while rep > 0 :
23
- if F [s [left ]] == 2 :
24
+ freqs [s [i ]] -= 1
25
+ if freqs [s [i ]] == 1 :
24
26
rep -= 1
25
- F [s [left ]] -= 1
26
- left += 1
27
27
28
- if right - left > ans :
29
- ans = right - left
28
+ i += 1
29
+
30
+ ans = max (ans , j - i + 1 )
30
31
31
32
return ans
You can’t perform that action at this time.
0 commit comments