[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)。相关文章推荐
- Lintcode_32 Minimum Window Substring
- [LeetCode] Minimum Window Substring -- python
- [leetcode]Minimum Window Substring @ Python
- lintcode-medium-Minimum Window Substring
- [LeetCode]题解(python):076-Minimum Window Substring
- [Lintcode]Minimum Window Substring
- LeetCode 76 Minimum Window Substring(Python详解及实现)
- Minimum Window Substring
- 【Leetcode】Minimum Window Substring
- [leetcode] Minimum Window Substring
- [leetcode]Minimum Window Substring
- LeetCode76 Minimum Window Substring(两种解法)
- LeetCode #76 - Minimum Window Substring
- Minimum Window Substring
- hrbust 1758 Minimum Window Substring【尺取法】好题
- Minimum Window Substring
- **LeetCode-Minimum Window Substring
- Minimum Window Substring
- Minimum Window Substring
- LeetCode OJ - Minimum Window Substring