diff --git a/076. Minimum Window Substring.py b/076. Minimum Window Substring.py index dda562c..c4c23a9 100644 --- a/076. Minimum Window Substring.py +++ b/076. Minimum Window Substring.py @@ -1,55 +1,46 @@ -# Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). - -# For example, -# S = "ADOBECODEBANC" -# T = "ABC" -# Minimum window is "BANC". - -# Note: -# If there is no such window in S that covers all characters in T, return the empty string "". - -# If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S. from collections import defaultdict class Solution(object): def minWindow(self, s, t): """ - O(N) + O(n) O(1) :type s: str :type t: str :rtype: str """ - if not s: - return "" - if not t: - return "" - useddict = defaultdict(int) + res = "" + if not s or not t: + return res + # init + dic = defaultdict(int) + # sliding windows + l,r = 0,0 + min_length = len(s) + size = len(t) for char in t: - useddict[char] += 1 + dic[char] += 1 - minlength = len(s) + 1 - length = len(t) - l, r = 0, 0 - res = "" - while r < len(s): - if s[r] in useddict: - useddict[s[r]] -= 1 - # only valid char in t will minus length - if useddict[s[r]] >= 0: - length -= 1 + if s[r] in dic: + if dic[s[r]] > 0: + size -= 1 + # value < 0 means duplicate char in s + dic[s[r]] -= 1 + r += 1 - while length == 0: - if minlength >= r-l: - minlength = r-l + + while size == 0: + if min_length >= r-l: + min_length = r-l res = s[l:r] - if s[l] in useddict: - useddict[s[l]] += 1 - # avoid duplicate - if useddict[s[l]] > 0: - length += 1 + # left bound + if s[l] in dic: + dic[s[l]] += 1 + if dic[s[l]] > 0: + size += 1 + l += 1 return res - + diff --git a/257. Binary Tree Paths.py b/257. Binary Tree Paths.py index 6a3ea30..3cec22a 100644 --- a/257. Binary Tree Paths.py +++ b/257. Binary Tree Paths.py @@ -13,11 +13,11 @@ # Credits: # Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. # Definition for a binary tree node. -# class TreeNode(object): -# def __init__(self, x): -# self.val = x -# self.left = None -# self.right = None +class TreeNode(object): + def __init__(self, x): + self.val = x + self.left = None + self.right = None class Solution(object): def binaryTreePaths(self, root): @@ -40,3 +40,4 @@ def helper(self, root, res, temp): self.helper(root.left, res, temp + '->'+str(root.left.val)) if root.right: self.helper(root.right, res , temp + '->'+str(root.right.val)) + diff --git a/494. Target Sum.py b/494. Target Sum.py index 9ece5c2..a1fa88e 100644 --- a/494. Target Sum.py +++ b/494. Target Sum.py @@ -44,4 +44,6 @@ def helper(self, nums, k): #print i dp[i] = dp[i] + dp[i-num] #print dp - return dp[k] \ No newline at end of file + return dp[k] +m = Solution() +print m.findTargetSumWays([1,1,1,1,1],3) \ No newline at end of file diff --git a/Wepay and OfferUp/014. Longest Common Prefix.py b/Wepay and OfferUp/014. Longest Common Prefix.py index 05888c3..cf27f5a 100644 --- a/Wepay and OfferUp/014. Longest Common Prefix.py +++ b/Wepay and OfferUp/014. Longest Common Prefix.py @@ -1,4 +1,9 @@ +# To remove only spaces use str.replace: +# sentence = sentence.replace(' ', '') +# To remove all whitespace characters (space, tab, newline, and so on) you can use split then join: + +# sentence = ''.join(sentence.split()) # Write a function to find the longest common prefix string amongst an array of strings. class Solution(object): def longestCommonPrefix(self, strs): diff --git a/Wepay and OfferUp/053. Maximum Subarray.py b/Wepay and OfferUp/053. Maximum Subarray.py new file mode 100644 index 0000000..2ee37ac --- /dev/null +++ b/Wepay and OfferUp/053. Maximum Subarray.py @@ -0,0 +1,35 @@ +# Find the contiguous subarray within an array (containing at least one number) which has the largest sum. + +# For example, given the array [-2,1,-3,4,-1,2,1,-5,4], +# the contiguous subarray [4,-1,2,1] has the largest sum = 6. +class Solution(object): + def maxSubArray(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + if not nums: + return 0 + if len(nums) == 1: + return nums[0] + index=0 + prevMax = nums[0] + res = nums[0] + for each in range(1,len(nums)): + prevMax = max(prevMax+nums[each], nums[each]) + if res < prevMax: + index = each + res = prevMax + #res = max(res, prevMax) + + print res + t = [] + while res!=0: + t.append(nums[index]) + + res -= nums[index] + index -= 1 + + return t[::-1] +m = Solution() +print m.maxSubArray([-2,1,-3,4,-1,2,1,-5,4]) \ No newline at end of file diff --git a/Wepay and OfferUp/065. Valid Number.py b/Wepay and OfferUp/065. Valid Number.py new file mode 100644 index 0000000..4f7dc43 --- /dev/null +++ b/Wepay and OfferUp/065. Valid Number.py @@ -0,0 +1,40 @@ +class Solution(object): + def isNumber(self, s): + """ + :type s: str + :rtype: bool + """ + begin, last = 0, len(s) - 1 + # + while begin <= last and s[begin] == ' ': + begin += 1 + while begin <= last and s[last] == ' ': + last -= 1 + + # + if begin < last and (s[begin] == '+' or s[begin] == '-'): + begin += 1 + num, dot, exp = False, False, False + + while begin <= last: + # + if s[begin] >= '0' and s[begin] <= '9': + num = True + # + elif s[begin] == '.': + if dot or exp: + return False + dot = True + # + elif s[begin] == 'e' or s[begin] == 'E': + if exp or not num: + return False + exp, num = True, False + # + elif s[begin] == '+' or s[begin] == '-': + if s[begin - 1] != 'e': + return False + else: + return False + begin += 1 + return num \ No newline at end of file diff --git a/Wepay and OfferUp/139. Word Break.py b/Wepay and OfferUp/139. Word Break.py new file mode 100644 index 0000000..03957ea --- /dev/null +++ b/Wepay and OfferUp/139. Word Break.py @@ -0,0 +1,28 @@ +# Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words. + +# For example, given +# s = "leetcode", +# dict = ["leet", "code"]. + +# Return true because "leetcode" can be segmented as "leet code". +class Solution(object): + def wordBreak(self, s, wordDict): + """ + :type s: str + :type wordDict: List[str] + :rtype: bool + """ + if not s: + return True + + # init + dp = [False for _ in range(len(s)+1)] + dp[0] = True + + for i in range(1,len(s)+1): + for j in range(i): + if dp[j] and s[j:i] in wordDict: + dp[i] = True + print dp + return dp[-1] + \ No newline at end of file diff --git a/Wepay and OfferUp/140. Word Break II.py b/Wepay and OfferUp/140. Word Break II.py new file mode 100644 index 0000000..7e961da --- /dev/null +++ b/Wepay and OfferUp/140. Word Break II.py @@ -0,0 +1,43 @@ +# Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. You may assume the dictionary does not contain duplicate words. + +# Return all such possible sentences. + +# For example, given +# s = "catsanddog", +# dict = ["cat", "cats", "and", "sand", "dog"]. + +# A solution is ["cats and dog", "cat sand dog"]. +class Solution(object): + def wordBreak(self, s, wordDict): + """ + :type s: str + :type wordDict: Set[str] + :rtype: List[str] + """ + ans = [] + if self.check(s, wordDict): + self.dfs(0, len(s), '', s, ans, wordDict) + return ans + + def check(self, s, wordDict): + dp = [True] + [False] * len(s) + n = len(s) + for i in xrange(n): + for j in xrange(i + 1): + if dp[j] and s[j:i + 1] in wordDict: + dp[i + 1] = True + break + return dp[n] + + def dfs(self, cur, n, path, s, ans, wordDict): + if cur == n: + #print path + ans.append(path) + return + + for i in xrange(cur, n): + if s[cur:i + 1] in wordDict and self.check(s[i + 1:n], wordDict): + if path: + self.dfs(i + 1, n, path + ' ' + s[cur:i + 1], s, ans, wordDict) + else: + self.dfs(i + 1, n, s[cur:i + 1], s, ans, wordDict) \ No newline at end of file diff --git a/Wepay and OfferUp/151. Reverse Words in a String.py b/Wepay and OfferUp/151. Reverse Words in a String.py new file mode 100644 index 0000000..5ff93ff --- /dev/null +++ b/Wepay and OfferUp/151. Reverse Words in a String.py @@ -0,0 +1,21 @@ +# Given an input string, reverse the string word by word. + +# For example, +# Given s = "the sky is blue", +# return "blue is sky the". + +class Solution(object): + def reverseWords(self, s): + """ + O(n) + O(n) + :type s: str + :rtype: str + """ + if not s: + return '' + li = s.strip().split() + res = [] + for each in range(len(li)-1,-1,-1): + res.append(li[each]) + return ' '.join(res) diff --git a/Wepay and OfferUp/151. Reverse Words in a StringII.py b/Wepay and OfferUp/151. Reverse Words in a StringII.py new file mode 100644 index 0000000..c9cac06 --- /dev/null +++ b/Wepay and OfferUp/151. Reverse Words in a StringII.py @@ -0,0 +1,24 @@ +class Solution(object): + def reverseWords(self, s): + """ + :type s: a list of 1 length strings (List[str]) + :rtype: nothing + """ + def reverse(s, begin, end): + for i in xrange((end - begin) / 2): + s[begin + i], s[end - 1 - i] = s[end - 1 - i], s[begin + i] + + reverse(s, 0, len(s)) + print s + i = 0 + for j in xrange(len(s) + 1): + if j == len(s) or s[j] == ' ': + reverse(s, i, j) + i = j + 1 + + +if __name__ == '__main__': + s = "the sky is blue" + b= list(s) + Solution().reverseWords(b) + print "".join(b) \ No newline at end of file diff --git a/Wepay and OfferUp/152. Maximum Product Subarray.py b/Wepay and OfferUp/152. Maximum Product Subarray.py new file mode 100644 index 0000000..376231c --- /dev/null +++ b/Wepay and OfferUp/152. Maximum Product Subarray.py @@ -0,0 +1,19 @@ +# Find the contiguous subarray within an array (containing at least one number) which has the largest product. + +# For example, given the array [2,3,-2,4], +# the contiguous subarray [2,3] has the largest product = 6. +class Solution(object): + def maxProduct(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + maxSoFar = nums[0] + maxEndingHere = nums[0] + minEndingHere = nums[0] + for i in range(1, len(nums)): + maxTemp = maxEndingHere + maxEndingHere = max(maxEndingHere * nums[i], nums[i], minEndingHere * nums[i]) + minEndingHere = min(minEndingHere * nums[i], nums[i], maxTemp * nums[i]) + maxSoFar = max(maxSoFar, maxEndingHere) + return maxSoFar \ No newline at end of file diff --git a/Wepay and OfferUp/153. Find Minimum in Rotated Sorted Array.py b/Wepay and OfferUp/153. Find Minimum in Rotated Sorted Array.py new file mode 100644 index 0000000..495979a --- /dev/null +++ b/Wepay and OfferUp/153. Find Minimum in Rotated Sorted Array.py @@ -0,0 +1,26 @@ +# Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. + +# (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). + +# Find the minimum element. + +# You may assume no duplicate exists in the array. +class Solution(object): + def findMin(self, nums): + """ + O(logn) + O(1) + :type nums: List[int] + :rtype: int + """ + left = 0 + right = len(nums)-1 + while left < right and nums[left]> nums[right]: + middle = left + (right-left)/2 + if nums[middle] > nums[right]: + # left-middle is increasing + left = middle + 1 + else: + right = middle + return nums[left] + diff --git a/Wepay and OfferUp/645. Set Mismatch.py b/Wepay and OfferUp/645. Set Mismatch.py new file mode 100644 index 0000000..d754ea3 --- /dev/null +++ b/Wepay and OfferUp/645. Set Mismatch.py @@ -0,0 +1,29 @@ +# The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number. + +# Given an array nums representing the data status of this set after the error. Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array. + +# Example 1: +# Input: nums = [1,2,2,4] +# Output: [2,3] +# Note: +# The given array size will in the range [2, 10000]. +# The given array's numbers won't have any order. +from collections import defaultdict +class Solution(object): + def findErrorNums(self, nums): + """ + O(n) + O(n) + :type nums: List[int] + :rtype: List[int] + """ + dic = defaultdict(int) + for num in nums: + dic[num] += 1 + for i in range(1, len(nums)+1): + if i in dic: + if dic[i] == 2: + dup = i + else: + missing = i + return [dup, missing] diff --git a/Wepay and OfferUp/LeafDoubleLinkedList.py b/Wepay and OfferUp/LeafDoubleLinkedList.py new file mode 100644 index 0000000..6cdaeb1 --- /dev/null +++ b/Wepay and OfferUp/LeafDoubleLinkedList.py @@ -0,0 +1,59 @@ +class DoublyListNode(object): + def __init__(self, val): + self.val = val + self.next = None + self.prev = None +class TreeNode(object): + def __init__(self, x): + self.val = x + self.left = None + self.right = None + +class Solution(object): + def levelOrder(self, root): + if not root: + return None + dummy = DoublyListNode(0) + head = dummy + tail = dummy + head.next = tail + tail.prev = head + leaf = [] + queue = [root] + while queue: + level = len(queue) + while level: + node = queue.pop(0) + if not node.left and not node.right: + t = DoublyListNode(node.val) + temp = tail.prev + temp.next = t + tail.prev = t + t.prev = temp + t.next = tail + leaf.append(node.val) + level -= 1 + break + if node.left: + queue.append(node.left) + if node.right: + queue.append(node.right) + + level -= 1 + + p = tail.prev + n = tail.next + p.next = n + n.prev = p + print dummy.next.val + print dummy.next.next.val + print dummy.next.next.next.val + return leaf + + +m = Solution() +tree = TreeNode(1) +tree.left = TreeNode(2) +tree.right = TreeNode(3) +tree.right.left = TreeNode(4) +print m.levelOrder(tree) \ No newline at end of file diff --git a/Wepay and OfferUp/findPath.py b/Wepay and OfferUp/findPath.py new file mode 100644 index 0000000..525c91e --- /dev/null +++ b/Wepay and OfferUp/findPath.py @@ -0,0 +1,60 @@ +class TreeNode(object): + def __init__(self, x): + self.val = x + self.left = None + self.right = None +class DoublyListNode(object): + def __init__(self, val): + self.val = val + self.next = None + self.prev = None +class Solution2(object): + def binaryTreePaths(self, root,node): + """ + :type root: TreeNode + :rtype: List[str] + """ + res = [] + if not root: + return res + self.helper(root, res, str(root.val),node) + dummy = DoublyListNode(0) + head = dummy + tail = dummy + head.next = tail + tail.prev = head + for i in res[0]: + t = DoublyListNode(int(i)) + temp = tail.prev + temp.next = t + tail.prev = t + t.prev = temp + t.next = tail + # delete dummy + p = tail.prev + n = tail.next + p.next = n + n.prev = p + print dummy.next.val + print dummy.next.next.val + print dummy.next.next.next.val + return res + def helper(self, root, res, temp,node): + if not root: + return + if root.val==node.val: + res.append(list(temp)) + return + if root.val>node.val: + if root.left: + self.helper(root.left, res, temp + str(root.left.val),node) + else: + if root.right: + self.helper(root.right, res , temp +str(root.right.val),node) + +m = Solution2() +tree = TreeNode(5) +tree.left = TreeNode(1) +tree.right = TreeNode(6) +tree.right.left = TreeNode(4) +print m.binaryTreePaths(tree,TreeNode(1)) \ No newline at end of file diff --git a/Wepay and OfferUp/foodmenu.py b/Wepay and OfferUp/foodmenu.py deleted file mode 100644 index 5ee3aee..0000000 --- a/Wepay and OfferUp/foodmenu.py +++ /dev/null @@ -1,25 +0,0 @@ -from collections import defaultdict - - -def foodmenu(order, menu): - res = defaultdict(int) - queue = [menu[order]] - while queue: - menu_list = queue.pop(0) - while menu_list: - item = menu_list.pop(0) - # item.values()-- [1] or ["meat":...] - if type(item.values()[0]) == type(1): - res[item.keys()[0]] += item.values()[0] - else: - # sub component {water:100} - for each in item.values()[0]: - menu_list.append(each) - return res - - - - - -menu = {"pizza":[{"floar":100},{"water":100},{"meat":[{"water":100}]}]} -print foodmenu("pizza", menu) \ No newline at end of file diff --git a/Wepay and OfferUp/printTreelevelOrder.py b/Wepay and OfferUp/printTreelevelOrder.py new file mode 100644 index 0000000..1a1c1f8 --- /dev/null +++ b/Wepay and OfferUp/printTreelevelOrder.py @@ -0,0 +1,59 @@ +# Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). + +# For example: +# Given binary tree [3,9,20,null,null,15,7], +# 3 +# / \ +# 9 20 +# / \ +# 15 7 +# return its level order traversal as: +# [ +# [3], +# [9,20], +# [15,7] +# ] +# Definition for a binary tree node. +class DoublyListNode(object): + def __init__(self, val): + self.val = val + self.next = None + self.prev = None +class TreeNode(object): + def __init__(self, x): + self.val = x + self.left = None + self.right = None + +class Solution(object): + def levelOrder(self, root): + if not root: + return None + res = [[root.val]] + queue = [root] + while queue: + level = len(queue) + temp = [] + while level: + node = queue.pop(0) + if not node.left: + temp.append(".") + if node.left: + queue.append(node.left) + temp.append(node.left.val) + if not node.right: + temp.append(".") + if node.right: + queue.append(node.right) + temp.append(node.right.val) + level -= 1 + res.append(list(temp)) # diff temp + + return res[:-1] + +m = Solution() +tree = TreeNode(1) +tree.left = TreeNode(2) +tree.right = TreeNode(3) +tree.right.left = TreeNode(4) +print m.levelOrder(tree) \ No newline at end of file