From 6c7d858a759c22e54394afaceb91cbed0b5554f5 Mon Sep 17 00:00:00 2001 From: jw2013 Date: Fri, 30 May 2014 22:32:12 -0400 Subject: [PATCH 1/2] add more solutions --- Decode Ways.py | 13 +++++++++ Distinct Subsequences.py | 11 ++++++++ Gas Station.py | 14 ++++++++++ Implement strStr().py | 11 ++++++++ Largest Rectangle in Histogram.py | 14 ++++++++++ ... Substring Without Repeating Characters.py | 14 ++++++++++ Longest Valid Parentheses.py | 15 +++++++++++ Maximal Rectangle.py | 27 +++++++++++++++++++ Permutation Sequence.py | 12 +++++++++ Sqrt(x).py | 10 +++++++ 10 files changed, 141 insertions(+) create mode 100644 Decode Ways.py create mode 100644 Distinct Subsequences.py create mode 100644 Gas Station.py create mode 100644 Implement strStr().py create mode 100644 Largest Rectangle in Histogram.py create mode 100644 Longest Substring Without Repeating Characters.py create mode 100644 Longest Valid Parentheses.py create mode 100644 Maximal Rectangle.py create mode 100644 Permutation Sequence.py create mode 100644 Sqrt(x).py diff --git a/Decode Ways.py b/Decode Ways.py new file mode 100644 index 0000000..b905ed7 --- /dev/null +++ b/Decode Ways.py @@ -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 \ No newline at end of file diff --git a/Distinct Subsequences.py b/Distinct Subsequences.py new file mode 100644 index 0000000..3ef3b6c --- /dev/null +++ b/Distinct Subsequences.py @@ -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)] \ No newline at end of file diff --git a/Gas Station.py b/Gas Station.py new file mode 100644 index 0000000..ca5c382 --- /dev/null +++ b/Gas Station.py @@ -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 \ No newline at end of file diff --git a/Implement strStr().py b/Implement strStr().py new file mode 100644 index 0000000..391e2e6 --- /dev/null +++ b/Implement strStr().py @@ -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 \ No newline at end of file diff --git a/Largest Rectangle in Histogram.py b/Largest Rectangle in Histogram.py new file mode 100644 index 0000000..6065fb8 --- /dev/null +++ b/Largest Rectangle in Histogram.py @@ -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 \ No newline at end of file diff --git a/Longest Substring Without Repeating Characters.py b/Longest Substring Without Repeating Characters.py new file mode 100644 index 0000000..8d75576 --- /dev/null +++ b/Longest Substring Without Repeating Characters.py @@ -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 \ No newline at end of file diff --git a/Longest Valid Parentheses.py b/Longest Valid Parentheses.py new file mode 100644 index 0000000..e0119de --- /dev/null +++ b/Longest Valid Parentheses.py @@ -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 \ No newline at end of file diff --git a/Maximal Rectangle.py b/Maximal Rectangle.py new file mode 100644 index 0000000..211715b --- /dev/null +++ b/Maximal Rectangle.py @@ -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 \ No newline at end of file diff --git a/Permutation Sequence.py b/Permutation Sequence.py new file mode 100644 index 0000000..0dde1f9 --- /dev/null +++ b/Permutation Sequence.py @@ -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 \ No newline at end of file diff --git a/Sqrt(x).py b/Sqrt(x).py new file mode 100644 index 0000000..138c1c1 --- /dev/null +++ b/Sqrt(x).py @@ -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) \ No newline at end of file From 85e822795da164a4fa6f4411f57d144b06d13845 Mon Sep 17 00:00:00 2001 From: jw2013 Date: Sun, 1 Jun 2014 22:22:53 -0400 Subject: [PATCH 2/2] add more solutions --- Binary Tree Maximum Path Sum.py | 13 +++++++++++++ Clone Graph.py | 19 +++++++++++++++++++ Insert Interval.py | 16 ++++++++++++++++ Merge Intervals.py | 13 +++++++++++++ Restore IP Addresses.py | 22 ++++++++++++++++++++++ Simplify Path.py | 10 ++++++++++ Word Search.py | 18 ++++++++++++++++++ ZigZag Conversion.py | 13 +++++++++++++ 8 files changed, 124 insertions(+) create mode 100644 Binary Tree Maximum Path Sum.py create mode 100644 Clone Graph.py create mode 100644 Insert Interval.py create mode 100644 Merge Intervals.py create mode 100644 Restore IP Addresses.py create mode 100644 Simplify Path.py create mode 100644 Word Search.py create mode 100644 ZigZag Conversion.py diff --git a/Binary Tree Maximum Path Sum.py b/Binary Tree Maximum Path Sum.py new file mode 100644 index 0000000..b48ad25 --- /dev/null +++ b/Binary Tree Maximum Path Sum.py @@ -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) \ No newline at end of file diff --git a/Clone Graph.py b/Clone Graph.py new file mode 100644 index 0000000..459cdb7 --- /dev/null +++ b/Clone Graph.py @@ -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 \ No newline at end of file diff --git a/Insert Interval.py b/Insert Interval.py new file mode 100644 index 0000000..57c3897 --- /dev/null +++ b/Insert Interval.py @@ -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 \ No newline at end of file diff --git a/Merge Intervals.py b/Merge Intervals.py new file mode 100644 index 0000000..90222af --- /dev/null +++ b/Merge Intervals.py @@ -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 \ No newline at end of file diff --git a/Restore IP Addresses.py b/Restore IP Addresses.py new file mode 100644 index 0000000..f355b4c --- /dev/null +++ b/Restore IP Addresses.py @@ -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 \ No newline at end of file diff --git a/Simplify Path.py b/Simplify Path.py new file mode 100644 index 0000000..3c1a08e --- /dev/null +++ b/Simplify Path.py @@ -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] \ No newline at end of file diff --git a/Word Search.py b/Word Search.py new file mode 100644 index 0000000..4243de2 --- /dev/null +++ b/Word Search.py @@ -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 \ No newline at end of file diff --git a/ZigZag Conversion.py b/ZigZag Conversion.py new file mode 100644 index 0000000..f2bd258 --- /dev/null +++ b/ZigZag Conversion.py @@ -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 \ No newline at end of file