Skip to content

Commit 5418c6d

Browse files
Merge pull request #1378 from printjin-gmailcom/main
[printjin-gmailcom] Week 05 Solutions
2 parents 081776d + 8d49797 commit 5418c6d

File tree

5 files changed

+86
-0
lines changed

5 files changed

+86
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
class Solution:
2+
def maxProfit(self, price):
3+
min_price = float('inf')
4+
max_profit = 0
5+
for price in prices:
6+
if price < min_price:
7+
min_price = price
8+
elif price - min_price > max_profit:
9+
max_profit = price - min_price
10+
return max_profit
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution:
2+
def encode(self, strs):
3+
res = ''
4+
for s in strs:
5+
res += str(len(s)) + '#' + s
6+
return res
7+
8+
def decode(self, s):
9+
res = []
10+
i = 0
11+
while i < len(s):
12+
j = i
13+
while s[j] != '#':
14+
j += 1
15+
length = int(s[i:j])
16+
res.append(s[j+1:j+1+length])
17+
i = j + 1 + length
18+
return res

group-anagrams/printjin-gmailcom.py

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
from collections import defaultdict
2+
3+
class Solution:
4+
def groupAnagrams(self, strs):
5+
anagrams = defaultdict(list)
6+
for word in strs:
7+
count = [0] * 26
8+
for c in word:
9+
count[ord(c) - ord('a')] += 1
10+
anagrams[tuple(count)].append(word)
11+
return list(anagrams.values())
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Trie:
2+
def __init__(self):
3+
self.trie = {}
4+
5+
def insert(self, word):
6+
node = self.trie
7+
for char in word:
8+
if char not in node:
9+
node[char] = {}
10+
node = node[char]
11+
node['#'] = {}
12+
13+
def search(self, word):
14+
node = self.trie
15+
for char in word:
16+
if char not in node:
17+
return False
18+
node = node[char]
19+
return '#' in node
20+
21+
def startsWith(self, prefix):
22+
node = self.trie
23+
for char in prefix:
24+
if char not in node:
25+
return False
26+
node = node[char]
27+
return True

word-break/printjin-gmailcom.py

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Solution:
2+
def wordBreak(self, s, wordDict):
3+
wordSet = set(wordDict)
4+
memo = {}
5+
6+
def backtrack(start):
7+
if start == len(s):
8+
return True
9+
if start in memo:
10+
return memo[start]
11+
12+
for end in range(start + 1, len(s) + 1):
13+
if s[start:end] in wordSet and backtrack(end):
14+
memo[start] = True
15+
return True
16+
17+
memo[start] = False
18+
return False
19+
20+
return backtrack(0)

0 commit comments

Comments
 (0)