#它的其他功能与dict相同,但会为一个不存在的键提供默认值,从而避免KeyError异常。 needs = collections.defaultdict(int) ans = []
for w in t: need[w] += 1 for strat inrange(0,stride): left = right = strat #指向当前步子的第一个下标 cnt = 0#记录窗口内满足要求得单词数 window = collections.defaultdict(int) while right < n: #右边界入窗 cur_right = s[right:right+stride] if cur_right in need: window[cur_right] += 1 if window[cur_right] == need[cur_right]: cnt += 1 # 左边界收缩 if right - left + stride > limit: cur_left = s[left:left+stride] if cur_right in need: if window[cur_left] == need[cur_left]: cnt -= 1 window[cur_left] -= 1 left += stride #采集答案 if right - left +stride == limit and cnt == len(need): ans.append(left) right += stride return ans
import collection defSliding Window(s,t): left = right = 0 valid = 0# 窗口内已凑齐的字符种类数量 window = collections.defaultdict(int) needs = collections.defaultdict(int) for w in t: needs[w] += 1 while right < len(s): #右边界入窗,对窗口内数据的一系列更新 window[s[right]] += 1 if window[s[right]] == need [s[right]]: valid += 1 # 注意,先判断再加
#判断左侧是否要收缩 while 需要收缩: #左边界移除窗口,进行窗口内数据更新 if window[s[left]] == need[s[left]]: valid -= 1 #先判断再减 window[s[left]] -= 1 left += 1# 注意左侧进行收缩