这道题就是用一个dictionary来跟踪有多少还需要Match的字母以及当前需要match的次数。 再用一个queue 来记录哪些字幕被Match了以及他们被match的顺序
from collections import defaultdict class Solution: # @param {string} s # @param {string} t # @return {string} def minWindow(self, s, t): dic = defaultdict(int) for c in list(t): dic[c] += 1 length, tmp, ans = len(t), [], s + "X" for i in range(0, len(s)): c = s[i] if c in dic: tmp.append(i) dic[c] -= 1 if dic[c] >= 0: length -= 1 if length == 0: while tmp != []: k = s[tmp[0]] if dic[k] < 0: dic[k] += 1 tmp.pop(0) else: break if i - tmp[0] < len(ans): ans = s[tmp[0]:i+1] k = s[tmp[0]] dic[k] += 1 tmp.pop(0) length += 1 if ans == s + "X": return "" return ans
时间: 2024-10-05 12:33:33