Decode String

Decode String

stack version - 32ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
def decodeString(self, s):
"""
:type s: str
:rtype: str
"""
stack = []
stack.append(["", 1])
num = ""
for ch in s:
if ch.isdigit():
num += ch
elif ch == '[':
stack.append(["", int(num)])
num = ""
elif ch == ']':
st, k = stack.pop()
stack[-1][0] += st*k
else:
stack[-1][0] += ch
return stack[0][0]

test code

1
2
In [109]: s = Solution(); t = s.decodeString("3[a]2[bc]"); print(t)
aaabcbc

leet code

Best Time to Buy and Sell Stock with Cooldown

Best Time to Buy and Sell Stock with Cooldown

O(n) version - 40ms

1
2
3
4
5
6
7
8
9
10
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
notHold, notHold_cooldown, hold = 0, float('-inf'), float('-inf')
for p in prices:
hold, notHold, notHold_cooldown = max(hold, notHold - p), max(notHold, notHold_cooldown), hold + p
return max(notHold, notHold_cooldown)

test code

1
2
In [103]: s = Solution(); t = s.maxProfit([1,2,3,0,2]); print(t)
3

leet code

Task Scheduler

Task Scheduler

collections version - 84ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import collections
class Solution:
def leastInterval(self, tasks, n):
"""
:type tasks: List[str]
:type n: int
:rtype: int
"""
d = collections.Counter(tasks)
counts = d.values()
longest = max(counts)
ans = (longest - 1) * (n + 1)
for cnt in counts:
ans += cnt == longest and 1 or 0
return max(len(tasks), ans)

test code

1
2
In [98]: s = Solution(); t = s.leastInterval(["A","A","A","B","B","B"], 2); print(t)
8

leet code

Minimum Path Sum

Minimum Path Sum

dp version - 52ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
m = len(grid)
n = len(grid[0])
for i in range(1, n):
grid[0][i] += grid[0][i-1]
for i in range(1, m):
grid[i][0] += grid[i-1][0]
for i in range(1, m):
for j in range(1, n):
grid[i][j] += min(grid[i-1][j], grid[i][j-1])
return grid[-1][-1]

test code

1
2
In [67]: s = Solution(); t = s.minPathSum([[1,3,1],[1,5,1],[4,2,1]]); print(t)
7

leet code