32. Minimum Window Substring
Given a string source and a string target, find the minimum window in source which will contain all the characters in target.
Example
For source = "ADOBECODEBANC"
, target = "ABC"
, the minimum window is "BANC"
Idea:
一个字典存储target,另一个字典动态更新source字符。遍历target,遍历的每个元素为左边界,尝试找到满足条件有边界。如果找到就有结果。
Code
class Solution:
"""
@param source : A string
@param target: A string
@return: A string denote the minimum window, return "" if there is no such a string
一个字典存储target,另一个字典动态更新source字符。遍历target,遍历的每个元素为左边界,
尝试找到满足条件有边界。如果找到就有结果。
"""
def minWindow(self, source , target):
# write your code here
if source is None:
return ""
targetHash = self.getTargetHash(target)
targetUniqueChars = len(targetHash)
matchedUniqueChars = 0
hash = {}
n = len(source)
j = 0
minLength = n + 1
minWindowString = ""
for i in range(n):
while j < n and matchedUniqueChars < targetUniqueChars:
if source[j] in targetHash: #找到字符
hash[source[j]] = hash.get(source[j], 0) + 1 #
if hash[source[j]] == targetHash[source[j]]:
matchedUniqueChars += 1
j += 1
if j - i < minLength and matchedUniqueChars == targetUniqueChars:
minLength = j - i
minWindowString = source[i:j]
if source[i] in targetHash:
if hash[source[i]] == targetHash[source[i]]:
matchedUniqueChars -= 1
hash[source[i]] -= 1
return minWindowString
def getTargetHash(self, target):
hash = {}
for c in target:
hash[c] = hash.get(c, 0) + 1
#dict.get(key[, default]) dict.get(key[,default]) 会查询字典中的key键,要是存在key键,则
#返回key键的值,要是没有key键,则返回 default, 若是没有 default,则返回 None。
return hash