Skip to content

Commit

Permalink
add more solutions
Browse files Browse the repository at this point in the history
  • Loading branch information
DefiPanda committed Jul 19, 2014
1 parent 0074abb commit 3240193
Show file tree
Hide file tree
Showing 18 changed files with 265 additions and 0 deletions.
13 changes: 13 additions & 0 deletions Binary Tree Maximum Path Sum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
class Solution:
maxSum = -2147483648
def maxPathSum(self, root):
self.maxPathRecur(root)
return self.maxSum

def maxPathRecur(self, root):
if root == None:
return 0
left = max(0, self.maxPathRecur(root.left))
right = max(0, self.maxPathRecur(root.right))
self.maxSum = max(self.maxSum, left + right + root.val)
return root.val + max(left, right)
19 changes: 19 additions & 0 deletions Clone Graph.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
class Solution:
def cloneGraph(self, node):
if node == None:
return None
start = UndirectedGraphNode(node.label)
map, current = {node: start}, [node]
while len(current) > 0:
next = []
for x in current:
for neighbor in x.neighbors:
if neighbor not in map:
neighbor_copy = UndirectedGraphNode(neighbor.label)
next.append(neighbor)
map[x].neighbors.append(neighbor_copy)
map[neighbor] = neighbor_copy
else:
map[x].neighbors.append(map[neighbor])
current = next
return start
13 changes: 13 additions & 0 deletions Decode Ways.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
class Solution:
def numDecodings(self, s):
if len(s) == 0:
return 0
prev, prev_prev = 1, 0
for i in range(len(s)):
current = 0
if s[i] != '0':
current = prev
if i > 0 and (s[i - 1] == "1" or (s[i - 1] == "2" and s[i] <= "6")):
current += prev_prev
prev, prev_prev = current, prev
return prev
11 changes: 11 additions & 0 deletions Distinct Subsequences.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
class Solution:
def numDistinct(self, S, T):
ways = [[0 for j in range(len(S) + 1)] for i in range(len(T) + 1)]
for i in range(len(S) + 1):
ways[0][i] = 1
for i in range(1, len(T) + 1):
for j in range(1, len(S) + 1):
ways[i][j] = ways[i][j - 1]
if T[i - 1] == S[j - 1]:
ways[i][j] += ways[i - 1][j - 1]
return ways[len(T)][len(S)]
14 changes: 14 additions & 0 deletions Gas Station.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
class Solution:
def canCompleteCircuit(self, gas, cost):
start, sum_so_far, sum = 0, 0, 0
for i in range(len(gas)):
diff = gas[i] - cost[i]
if sum_so_far + diff < 0:
start = i + 1
sum_so_far = 0
else:
sum_so_far += diff
sum += diff
if sum >= 0:
return start
return -1
11 changes: 11 additions & 0 deletions Implement strStr().py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
class Solution:
def strStr(self, haystack, needle):
for i in range(len(haystack) - len(needle) + 1):
found = True
for j in range(len(needle)):
if haystack[i + j] != needle[j]:
found = False
break
if found:
return haystack[i:]
return None
16 changes: 16 additions & 0 deletions Insert Interval.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
class Solution:
def insert(self, intervals, newInterval):
return self.merge(intervals + [newInterval])

def merge(self, intervals):
if len(intervals) == 0:
return intervals
intervals.sort(key = lambda x: x.start)
result = [intervals[0]]
for i in range(1, len(intervals)):
current, prev = intervals[i], result[-1]
if current.start <= prev.end:
prev.end = max(prev.end, current.end)
else:
result.append(current)
return result
14 changes: 14 additions & 0 deletions Largest Rectangle in Histogram.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
class Solution:
def largestRectangleArea(self, height):
increasing, area, i = [], 0, 0
while i <= len(height):
if len(increasing) == 0 or (i < len(height) and height[i] > height[increasing[-1]]):
increasing.append(i)
i += 1
else:
last = increasing.pop()
if len(increasing) == 0:
area = max(area, height[last] * i)
else:
area = max(area, height[last] * (i - increasing[-1] - 1))
return area
14 changes: 14 additions & 0 deletions Longest Substring Without Repeating Characters.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
class Solution:
def lengthOfLongestSubstring(self, s):
count, start, longest = [False for i in range(256)], 0, 0
for i in range(len(s)):
if count[ord(s[i])] == False:
count[ord(s[i])] = True
else:
longest = max(i - start, longest)
while s[start] != s[i]:
count[ord(s[start])] = False
start += 1
start += 1
longest = max(len(s) - start, longest)
return longest
15 changes: 15 additions & 0 deletions Longest Valid Parentheses.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
class Solution:
def longestValidParentheses(self, s):
longest, last, indices = 0, 0, []
for i in range(len(s)):
if s[i] == '(':
indices.append(i)
elif len(indices) == 0:
last = i + 1
else:
index = indices.pop()
if len(indices) == 0:
longest = max(longest, i - last + 1)
else:
longest = max(longest, i - indices[-1])
return longest
27 changes: 27 additions & 0 deletions Maximal Rectangle.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
class Solution:
def maximalRectangle(self, matrix):
heights = [[0 for j in range(len(matrix[0]))] for i in range(len(matrix))]
for i in range(0, len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == "0":
heights[i][j] = 0
elif i == 0:
heights[i][j] = 1
else:
heights[i][j] = int(heights[i - 1][j]) + 1
return reduce(lambda acc, i: max(acc, self.largestRectangleArea(heights[i])), range(len(heights)), 0)

# This is the solution for question Largest Rectangle in Histogram
def largestRectangleArea(self, height):
increasing, area, i = [], 0, 0
while i <= len(height):
if len(increasing) == 0 or (i < len(height) and height[i] > height[increasing[-1]]):
increasing.append(i)
i += 1
else:
last = increasing.pop()
if len(increasing) == 0:
area = max(area, height[last] * i)
else:
area = max(area, height[last] * (i - increasing[-1] - 1))
return area
13 changes: 13 additions & 0 deletions Merge Intervals.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
class Solution:
def merge(self, intervals):
if len(intervals) == 0:
return intervals
intervals.sort(key = lambda x: x.start)
result = [intervals[0]]
for i in range(1, len(intervals)):
current, prev = intervals[i], result[-1]
if current.start <= prev.end:
prev.end = max(prev.end, current.end)
else:
result.append(current)
return result
12 changes: 12 additions & 0 deletions Permutation Sequence.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
class Solution:
def getPermutation(self, n, k):
seq, k, fact = "", k - 1, math.factorial(n - 1)
perm = [i for i in range(1, n + 1)]
for i in reversed(range(n)):
curr = perm[k / fact]
seq += str(curr)
perm.remove(curr)
if i > 0:
k %= fact
fact /= i
return seq
22 changes: 22 additions & 0 deletions Restore IP Addresses.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
class Solution:
def restoreIpAddresses(self, s):
result = []
self.restoreIpAddressesRecur(result, s, "", 0)
return result

def restoreIpAddressesRecur(self, result, s, current, dots):
# pruning to improve performance
if (4 - dots) * 3 < len(s):
return
if dots == 3:
if self.isValid(s):
result.append(current + s)
else:
for i in range(3):
if len(s) > i and self.isValid(s[:i + 1]):
self.restoreIpAddressesRecur(result, s[i + 1:], current + s[:i + 1] + '.', dots + 1)

def isValid(self, s):
if len(s) == 0 or (s[0] == "0" and s != "0"):
return False
return int(s) < 256
10 changes: 10 additions & 0 deletions Simplify Path.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
class Solution:
def simplifyPath(self, path):
stack, tokens = [], path.split('/')
for token in tokens:
if token == "..":
if len(stack) > 0:
stack.pop()
elif token != "" and token != ".":
stack.append(token)
return "/" + reduce(lambda acc, x: acc + x + "/", stack, "")[:-1]
10 changes: 10 additions & 0 deletions Sqrt(x).py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
class Solution:
def sqrt(self, x):
low, high = 0, x / 2 + 1
while high >= low:
mid = (high + low) / 2
if x < mid * mid:
high = mid - 1
else:
low = mid + 1
return int(high)
18 changes: 18 additions & 0 deletions Word Search.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
class Solution:
def exist(self, board, word):
visited = [[0 for y in range(len(board[0]))] for x in range(len(board))]
for i in range(len(board)):
for j in range(len(board[0])):
if self.existRecur(board, word, visited, i, j) == True:
return True
return False

def existRecur(self, board, word, visited, i, j):
if len(word) == 0:
return True
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]:
return False
visited[i][j] = 1
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)
visited[i][j] = 0
return found
13 changes: 13 additions & 0 deletions ZigZag Conversion.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
class Solution:
def convert(self, s, nRows):
step, zigzag = 2 * nRows - 2, ""
if s == None or len(s) == 0 or nRows <= 0:
return ""
if nRows == 1:
return s
for i in range(nRows):
for j in range(i, len(s), step):
zigzag += s[j]
if i > 0 and i < nRows - 1 and j + step - 2 * i < len(s):
zigzag += s[j + step - 2 * i]
return zigzag

0 comments on commit 3240193

Please sign in to comment.