File tree Expand file tree Collapse file tree 2 files changed +58
-0
lines changed
longest-substring-without-repeating-characters Expand file tree Collapse file tree 2 files changed +58
-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
Original file line number Diff line number Diff line change
1
+ # Definition for singly-linked list.
2
+ # class ListNode:
3
+ # def __init__(self, val=0, next=None):
4
+ # self.val = val
5
+ # self.next = next
6
+ class Solution :
7
+ def reverseList (self , head : Optional [ListNode ]) -> Optional [ListNode ]:
8
+ # time complexity: O(n) / memory complexity: O(n)
9
+ stack = []
10
+ current = head
11
+ while current :
12
+ stack .append (current .val )
13
+ current = current .next
14
+
15
+ dummy_head = ListNode ()
16
+ current = dummy_head
17
+ while stack :
18
+ current .next = ListNode (val = stack .pop (), next = None )
19
+ current = current .next
20
+ return dummy_head .next
You can’t perform that action at this time.
0 commit comments