Skip to content

Commit f30bebf

Browse files
Merge pull request #1891 from prograsshopper/main
[prograsshopper] week 7 solutions
2 parents 4c5e27c + 1f7fba9 commit f30bebf

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
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

0 commit comments

Comments
 (0)