Skip to content

Commit 3240193

Browse files
committed
add more solutions
1 parent 0074abb commit 3240193

18 files changed

+265
-0
lines changed

Binary Tree Maximum Path Sum.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
class Solution:
2+
maxSum = -2147483648
3+
def maxPathSum(self, root):
4+
self.maxPathRecur(root)
5+
return self.maxSum
6+
7+
def maxPathRecur(self, root):
8+
if root == None:
9+
return 0
10+
left = max(0, self.maxPathRecur(root.left))
11+
right = max(0, self.maxPathRecur(root.right))
12+
self.maxSum = max(self.maxSum, left + right + root.val)
13+
return root.val + max(left, right)

Clone Graph.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution:
2+
def cloneGraph(self, node):
3+
if node == None:
4+
return None
5+
start = UndirectedGraphNode(node.label)
6+
map, current = {node: start}, [node]
7+
while len(current) > 0:
8+
next = []
9+
for x in current:
10+
for neighbor in x.neighbors:
11+
if neighbor not in map:
12+
neighbor_copy = UndirectedGraphNode(neighbor.label)
13+
next.append(neighbor)
14+
map[x].neighbors.append(neighbor_copy)
15+
map[neighbor] = neighbor_copy
16+
else:
17+
map[x].neighbors.append(map[neighbor])
18+
current = next
19+
return start

Decode Ways.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
class Solution:
2+
def numDecodings(self, s):
3+
if len(s) == 0:
4+
return 0
5+
prev, prev_prev = 1, 0
6+
for i in range(len(s)):
7+
current = 0
8+
if s[i] != '0':
9+
current = prev
10+
if i > 0 and (s[i - 1] == "1" or (s[i - 1] == "2" and s[i] <= "6")):
11+
current += prev_prev
12+
prev, prev_prev = current, prev
13+
return prev

Distinct Subsequences.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
class Solution:
2+
def numDistinct(self, S, T):
3+
ways = [[0 for j in range(len(S) + 1)] for i in range(len(T) + 1)]
4+
for i in range(len(S) + 1):
5+
ways[0][i] = 1
6+
for i in range(1, len(T) + 1):
7+
for j in range(1, len(S) + 1):
8+
ways[i][j] = ways[i][j - 1]
9+
if T[i - 1] == S[j - 1]:
10+
ways[i][j] += ways[i - 1][j - 1]
11+
return ways[len(T)][len(S)]

Gas Station.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class Solution:
2+
def canCompleteCircuit(self, gas, cost):
3+
start, sum_so_far, sum = 0, 0, 0
4+
for i in range(len(gas)):
5+
diff = gas[i] - cost[i]
6+
if sum_so_far + diff < 0:
7+
start = i + 1
8+
sum_so_far = 0
9+
else:
10+
sum_so_far += diff
11+
sum += diff
12+
if sum >= 0:
13+
return start
14+
return -1

Implement strStr().py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
class Solution:
2+
def strStr(self, haystack, needle):
3+
for i in range(len(haystack) - len(needle) + 1):
4+
found = True
5+
for j in range(len(needle)):
6+
if haystack[i + j] != needle[j]:
7+
found = False
8+
break
9+
if found:
10+
return haystack[i:]
11+
return None

Insert Interval.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class Solution:
2+
def insert(self, intervals, newInterval):
3+
return self.merge(intervals + [newInterval])
4+
5+
def merge(self, intervals):
6+
if len(intervals) == 0:
7+
return intervals
8+
intervals.sort(key = lambda x: x.start)
9+
result = [intervals[0]]
10+
for i in range(1, len(intervals)):
11+
current, prev = intervals[i], result[-1]
12+
if current.start <= prev.end:
13+
prev.end = max(prev.end, current.end)
14+
else:
15+
result.append(current)
16+
return result

Largest Rectangle in Histogram.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class Solution:
2+
def largestRectangleArea(self, height):
3+
increasing, area, i = [], 0, 0
4+
while i <= len(height):
5+
if len(increasing) == 0 or (i < len(height) and height[i] > height[increasing[-1]]):
6+
increasing.append(i)
7+
i += 1
8+
else:
9+
last = increasing.pop()
10+
if len(increasing) == 0:
11+
area = max(area, height[last] * i)
12+
else:
13+
area = max(area, height[last] * (i - increasing[-1] - 1))
14+
return area
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class Solution:
2+
def lengthOfLongestSubstring(self, s):
3+
count, start, longest = [False for i in range(256)], 0, 0
4+
for i in range(len(s)):
5+
if count[ord(s[i])] == False:
6+
count[ord(s[i])] = True
7+
else:
8+
longest = max(i - start, longest)
9+
while s[start] != s[i]:
10+
count[ord(s[start])] = False
11+
start += 1
12+
start += 1
13+
longest = max(len(s) - start, longest)
14+
return longest

Longest Valid Parentheses.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
class Solution:
2+
def longestValidParentheses(self, s):
3+
longest, last, indices = 0, 0, []
4+
for i in range(len(s)):
5+
if s[i] == '(':
6+
indices.append(i)
7+
elif len(indices) == 0:
8+
last = i + 1
9+
else:
10+
index = indices.pop()
11+
if len(indices) == 0:
12+
longest = max(longest, i - last + 1)
13+
else:
14+
longest = max(longest, i - indices[-1])
15+
return longest

Maximal Rectangle.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution:
2+
def maximalRectangle(self, matrix):
3+
heights = [[0 for j in range(len(matrix[0]))] for i in range(len(matrix))]
4+
for i in range(0, len(matrix)):
5+
for j in range(len(matrix[0])):
6+
if matrix[i][j] == "0":
7+
heights[i][j] = 0
8+
elif i == 0:
9+
heights[i][j] = 1
10+
else:
11+
heights[i][j] = int(heights[i - 1][j]) + 1
12+
return reduce(lambda acc, i: max(acc, self.largestRectangleArea(heights[i])), range(len(heights)), 0)
13+
14+
# This is the solution for question Largest Rectangle in Histogram
15+
def largestRectangleArea(self, height):
16+
increasing, area, i = [], 0, 0
17+
while i <= len(height):
18+
if len(increasing) == 0 or (i < len(height) and height[i] > height[increasing[-1]]):
19+
increasing.append(i)
20+
i += 1
21+
else:
22+
last = increasing.pop()
23+
if len(increasing) == 0:
24+
area = max(area, height[last] * i)
25+
else:
26+
area = max(area, height[last] * (i - increasing[-1] - 1))
27+
return area

Merge Intervals.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
class Solution:
2+
def merge(self, intervals):
3+
if len(intervals) == 0:
4+
return intervals
5+
intervals.sort(key = lambda x: x.start)
6+
result = [intervals[0]]
7+
for i in range(1, len(intervals)):
8+
current, prev = intervals[i], result[-1]
9+
if current.start <= prev.end:
10+
prev.end = max(prev.end, current.end)
11+
else:
12+
result.append(current)
13+
return result

Permutation Sequence.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
class Solution:
2+
def getPermutation(self, n, k):
3+
seq, k, fact = "", k - 1, math.factorial(n - 1)
4+
perm = [i for i in range(1, n + 1)]
5+
for i in reversed(range(n)):
6+
curr = perm[k / fact]
7+
seq += str(curr)
8+
perm.remove(curr)
9+
if i > 0:
10+
k %= fact
11+
fact /= i
12+
return seq

Restore IP Addresses.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution:
2+
def restoreIpAddresses(self, s):
3+
result = []
4+
self.restoreIpAddressesRecur(result, s, "", 0)
5+
return result
6+
7+
def restoreIpAddressesRecur(self, result, s, current, dots):
8+
# pruning to improve performance
9+
if (4 - dots) * 3 < len(s):
10+
return
11+
if dots == 3:
12+
if self.isValid(s):
13+
result.append(current + s)
14+
else:
15+
for i in range(3):
16+
if len(s) > i and self.isValid(s[:i + 1]):
17+
self.restoreIpAddressesRecur(result, s[i + 1:], current + s[:i + 1] + '.', dots + 1)
18+
19+
def isValid(self, s):
20+
if len(s) == 0 or (s[0] == "0" and s != "0"):
21+
return False
22+
return int(s) < 256

Simplify Path.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
class Solution:
2+
def simplifyPath(self, path):
3+
stack, tokens = [], path.split('/')
4+
for token in tokens:
5+
if token == "..":
6+
if len(stack) > 0:
7+
stack.pop()
8+
elif token != "" and token != ".":
9+
stack.append(token)
10+
return "/" + reduce(lambda acc, x: acc + x + "/", stack, "")[:-1]

Sqrt(x).py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
class Solution:
2+
def sqrt(self, x):
3+
low, high = 0, x / 2 + 1
4+
while high >= low:
5+
mid = (high + low) / 2
6+
if x < mid * mid:
7+
high = mid - 1
8+
else:
9+
low = mid + 1
10+
return int(high)

Word Search.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution:
2+
def exist(self, board, word):
3+
visited = [[0 for y in range(len(board[0]))] for x in range(len(board))]
4+
for i in range(len(board)):
5+
for j in range(len(board[0])):
6+
if self.existRecur(board, word, visited, i, j) == True:
7+
return True
8+
return False
9+
10+
def existRecur(self, board, word, visited, i, j):
11+
if len(word) == 0:
12+
return True
13+
if i >= len(board) or j >= len(board[0]) or i < 0 or j < 0 or visited[i][j] == 1 or board[i][j] != word[0]:
14+
return False
15+
visited[i][j] = 1
16+
found = self.existRecur(board, word[1:], visited, i + 1, j) or self.existRecur(board, word[1:], visited, i - 1, j) or self.existRecur(board, word[1:], visited, i, j + 1) or self.existRecur(board, word[1:], visited, i, j - 1)
17+
visited[i][j] = 0
18+
return found

ZigZag Conversion.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
class Solution:
2+
def convert(self, s, nRows):
3+
step, zigzag = 2 * nRows - 2, ""
4+
if s == None or len(s) == 0 or nRows <= 0:
5+
return ""
6+
if nRows == 1:
7+
return s
8+
for i in range(nRows):
9+
for j in range(i, len(s), step):
10+
zigzag += s[j]
11+
if i > 0 and i < nRows - 1 and j + step - 2 * i < len(s):
12+
zigzag += s[j + step - 2 * i]
13+
return zigzag

0 commit comments

Comments
 (0)