小黑根据题解思路,独立写出代码
class Solution:
def minWindow(self, s: str, t: str) -> str:
# 两个字符串的长度
n_s = len(s)
n_t = len(t)
if n_s < n_t:
return ''
# 寻找初始的解,之后进行滑动窗口迭代
# 计数字典与计数变量
map_ = collections.Counter(t)
count_map = collections.Counter(t)
count = n_t
# 头尾指针
head = 0
tail = 0
# 是否找到初始位置
flag = False
# 最优解
result = n_t + n_s
result_s = ''
while tail < n_s:
if not flag:
if count_map.get(s[tail]):
count_map[s[tail]] -= 1
count -= 1
# 初始条件找到
if not count:
count = n_t
# 重构计数字典,为当前窗口的字符统计
count_map = collections.Counter(s[:tail+1])
flag = True
tail += 1
if flag:
# 扩大窗口
while count < n_t and tail < n_s:
if map_.get(s[tail]):
count_map[s[tail]] += 1
if count_map[s[tail]] == map_[s[tail]]:
count += 1
tail += 1
# 缩小窗口
while count == n_t:
if tail - head < result:
result = tail - head
result_s = s[head:tail]
# 扔掉窗口前置字符
if count_map.get(s[head]):
count_map[s[head]] -= 1
if count_map[s[head]] < map_[s[head]]:
count -= 1
head += 1
return result_s
双指针滑动窗口法
class Solution:
def minWindow(self, s: str, t: str) -> str:
# 两个字符串长度
n_s = len(s)
n_t = len(t)
if n_s < n_t:
return ''
# 定义计数字典
count_t = collections.Counter(t)
count_map = collections.defaultdict(int)
# 定义双指针
head = 0
tail = 0
# 结果
result = n_s + n_t
result_s = ''
# 开始迭代
while tail < n_s:
count_map[s[tail]] += 1
# 移动head指针
while self.check(count_t, count_map):
if tail - head + 1 < result:
result = tail - head + 1
result_s = s[head:tail+1]
count_map[s[head]] -= 1
head += 1
tail += 1
return result_s
def check(self, count_t, count_map):
for key in count_t:
if count_map[key] < count_t[key]:
return False
return True
小黑生活
准备小黄车骑天津的晚餐,节俭的我们拿碗喝饮料
出发骑车去天津
骑完车智齿犯了,去搓了澡,点了止疼药外卖
坐高铁回北京
那晚的流星
帐篷到了
早餐牙疼,吃宇飞牛肉面
按摩+拔罐
来个雪顶咖啡
去医院看牙,没拔成
挂了朝阳医院的号
得知19号就要清宿舍了
小汤3《日出》打卡
晚餐忍牙痛吃烤冷面
小黑被牙痛折磨的受不了,晚上跟老黑们试帐篷
忍痛吃午饭拔牙
手术恢复的不错
拔牙报销
学费和住宿费的发票单子
收到毕业照
一起出去喝嘉禾一品粥,逛万达小吃街
学校新开的理发店
回去小整一下,感谢阿黄买的酸梅汤
卖点东西
午餐卤煮驴肉火烧外卖
咖啡甜点刷算法
晚上和室友吃山城辣妹子
学校的空地上搭帐篷
毕业典礼错过了,一起拍个照
感谢小元同学冰棍
晚上萨莉亚+汗蒸,讨论新疆计划
度过了五号楼的最后一晚,领取了证书,补办了团员证
给大老黑寄证书。圆通改成了顺丰
宿舍小搞一下
离开了学校
去姥姥家吃火锅
准备出发去淄博啦
到达牧羊村烧烤
早餐五花肉烧饼
去济南吃午饭
准备回家
晚上吃烧烤牛肉面
中午继续吃芝麻开火锅
咖啡读书
按摩一小时
跟小悦和小露同学出去骑车
新增动漫
钢琴《黄鼠狼逃跑了》
喜茶大杯多肉葡萄
新书到了
朝阳公园慢跑+三里屯喜茶
破费来波儿新疆游
明日继续刷题,顺便更新厦门+重庆的旅行,希望能早起
\