File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
longest-substring-without-repeating-characters Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution :
2+ def lengthOfLongestSubstring (self , s : str ) -> int :
3+ # sol 1
4+ # time complexity: O(n^2) / memory complexity: O(n)
5+ if len (s ) in [0 , 1 ]:
6+ return len (s )
7+
8+ from collections import defaultdict
9+ strings = []
10+ for i in range (0 , len (s ) - 1 ):
11+ char_dict = defaultdict (int )
12+ char_dict [s [i ]] += 1
13+ for j in range (i + 1 , len (s )):
14+ char_dict [s [j ]] += 1
15+ if char_dict [s [j ]] > 1 :
16+ strings .append (s [i :j ])
17+ break
18+ else :
19+ strings .append (s [i :])
20+
21+ max_len = len (strings [0 ])
22+ for elem in strings :
23+ max_len = max (max_len , len (elem ))
24+ return max_len
25+
26+ # sol 2
27+ # time complexity: O(n) / memory complexity: O(n)
28+ str_set = set ()
29+ left = 0
30+ max_len = 0
31+
32+ for right in range (len (s )):
33+ while s [right ] in str_set :
34+ str_set .remove (s [left ])
35+ left += 1
36+ str_set .add (s [right ])
37+ max_len = max (max_len , right - left + 1 )
38+ return max_len
You can’t perform that action at this time.
0 commit comments