您的位置:首页 > 编程语言 > Python开发

[LintCode 32] Minimum Window Substring(Python)

2017-11-14 20:41 309 查看

题目描述

Given a string source and a string target, find the minimum window in source which will contain all the characters in target.

Notice

If there is no such window in source that covers all characters in target, return the emtpy string “”.

思路

用一字典存储target字符串,另一字典动态更新source字符串。遍历target,以遍历到的每个元素做左边界,尝试找到满足条件的右边界,如果找到就更新结果。

代码

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
"""
def minWindow(self, source , target):
# write your code here
if not source or not target or len(source) < len(target) or len(source) * len(target) == 0:
return ""
dt, ds = dict.fromkeys(target, 0), {}
for c in target: dt[c] += 1
res = ""
max_length = 2 ** 31
right = 0
for i, c in enumerate(source):
while (not self.valid(dt, ds)) and right < len(source):
ds[source[right]] = ds.get(source[right], 0) + 1
right += 1
if self.valid(dt, ds) and max_length > right - i:
max_length = right - i
res = source[i : right]
ds[c] -= 1
return res

def valid(self, dt, ds):
for k in dt:
if k not in ds or ds[k] < dt[k]:
return False
return True


复杂度分析

时间复杂度O(n),空间复杂度O(1)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: