Skip to content

Commit

Permalink
1211
Browse files Browse the repository at this point in the history
  • Loading branch information
youhusky committed Dec 12, 2017
1 parent ba9edca commit 9a34fef
Show file tree
Hide file tree
Showing 17 changed files with 485 additions and 68 deletions.
65 changes: 28 additions & 37 deletions 076. Minimum Window Substring.py
Original file line number Diff line number Diff line change
@@ -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


11 changes: 6 additions & 5 deletions 257. Binary Tree Paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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))

4 changes: 3 additions & 1 deletion 494. Target Sum.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,6 @@ def helper(self, nums, k):
#print i
dp[i] = dp[i] + dp[i-num]
#print dp
return dp[k]
return dp[k]
m = Solution()
print m.findTargetSumWays([1,1,1,1,1],3)
5 changes: 5 additions & 0 deletions Wepay and OfferUp/014. Longest Common Prefix.py
Original file line number Diff line number Diff line change
@@ -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):
Expand Down
35 changes: 35 additions & 0 deletions Wepay and OfferUp/053. Maximum Subarray.py
Original file line number Diff line number Diff line change
@@ -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])
40 changes: 40 additions & 0 deletions Wepay and OfferUp/065. Valid Number.py
Original file line number Diff line number Diff line change
@@ -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
28 changes: 28 additions & 0 deletions Wepay and OfferUp/139. Word Break.py
Original file line number Diff line number Diff line change
@@ -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]

43 changes: 43 additions & 0 deletions Wepay and OfferUp/140. Word Break II.py
Original file line number Diff line number Diff line change
@@ -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)
21 changes: 21 additions & 0 deletions Wepay and OfferUp/151. Reverse Words in a String.py
Original file line number Diff line number Diff line change
@@ -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)
24 changes: 24 additions & 0 deletions Wepay and OfferUp/151. Reverse Words in a StringII.py
Original file line number Diff line number Diff line change
@@ -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)
19 changes: 19 additions & 0 deletions Wepay and OfferUp/152. Maximum Product Subarray.py
Original file line number Diff line number Diff line change
@@ -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
26 changes: 26 additions & 0 deletions Wepay and OfferUp/153. Find Minimum in Rotated Sorted Array.py
Original file line number Diff line number Diff line change
@@ -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]

Loading

0 comments on commit 9a34fef

Please sign in to comment.