题目描述:
方法一:O(MN)
class Solution: def minWindow(self, s: 'str', t: 'str') -> 'str': from collections import Counter t = Counter(t) lookup = Counter() start = 0 end = 0 min_len = float("inf") res = "" while end < len(s): lookup[s[end]] += 1 end += 1 #print(start, end) while all(map(lambda x: lookup[x] >= t[x], t.keys())): if end - start < min_len: res = s[start:end] min_len = end - start lookup[s[start]] -= 1 start += 1 return res
方法二:O(M+N)
class Solution: def minWindow(self, s: 'str', t: 'str') -> 'str': from collections import defaultdict lookup = defaultdict(int) for c in t: lookup[c] += 1 start = 0 end = 0 min_len = float("inf") counter = len(t) res = "" while end < len(s): if lookup[s[end]] > 0: counter -= 1 lookup[s[end]] -= 1 end += 1 while counter == 0: if min_len > end - start: min_len = end - start res = s[start:end] if lookup[s[start]] == 0: counter += 1 lookup[s[start]] += 1 start += 1 return res