[LintCode 32] Minimum Window Substring(Python)

来源:互联网 发布:马士兵java基础教程 编辑:程序博客网 时间:2024/06/07 21:27

题目描述

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)

原创粉丝点击