Skip to content

Commit 0381604

Browse files
authored
[njngwn] WEEK 05 Solutions (#2775)
* solve valid anagram * solve climbing stairs * solve best time to buy and sell stock * solve group anagrams * solve encode and decode strings * solve word break
1 parent ce7cc62 commit 0381604

4 files changed

Lines changed: 68 additions & 0 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
class Solution:
2+
# Time Complexity: O(n), n: len(prices)
3+
# Space Complexity: O(1)
4+
def maxProfit(self, prices: List[int]) -> int:
5+
min_price = prices[0]
6+
profit = 0
7+
8+
for i in range(1, len(prices)):
9+
min_price = min(min_price, prices[i])
10+
profit = max(profit, prices[i] - min_price)
11+
12+
return profit
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution:
2+
3+
def encode(self, strs: List[str]) -> str:
4+
encoded = ''
5+
6+
for s in strs:
7+
encoded += str(len(s)) + '#' + s
8+
9+
return encoded
10+
11+
def decode(self, s: str) -> List[str]:
12+
decoded = []
13+
14+
i = 0
15+
while i < len(s):
16+
j = i # j is a pointer for beginning of string
17+
# find '#' in string
18+
while s[j] != '#':
19+
j += 1
20+
21+
length = int(s[i:j])
22+
word = s[j + 1:j + length + 1]
23+
decoded.append(word)
24+
i = j + length + 1
25+
26+
return decoded

group-anagrams/njngwn.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class Solution:
2+
# Time Complexity: O(n), n: len(strs)
3+
# Space Complexity: O(n), n: len(strs)
4+
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
5+
anagram_groups = dict() # key: string in an alphabetical order, values: strings
6+
7+
for s in strs:
8+
word = ''.join(sorted(s))
9+
if word in anagram_groups:
10+
anagram_groups[word].extend([s])
11+
else:
12+
anagram_groups[word] = [s]
13+
14+
return list(anagram_groups.values())

word-break/njngwn.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
from functools import cache
2+
3+
4+
class Solution:
5+
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
6+
@cache
7+
def check(cur):
8+
if cur == len(s):
9+
return True
10+
for word in wordDict:
11+
if s[cur: cur + len(word)] == word:
12+
if check(cur + len(word)):
13+
return True
14+
return False
15+
16+
return check(0)

0 commit comments

Comments
 (0)