76. Minimum Window Substring

题目描述

Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string “”.

The testcases will be generated such that the answer is unique.

A substring is a contiguous sequence of characters within the string.

解题思路

看到时间复杂度的要求,第一时间想到的是能不能用空间换时间。常用的方法就是字典,一遍遍历过去,我们想尽快的知道我们目前的一个解(有可能是次优解),与目标串 t 的关系究竟如何,也就是说,当前的解是不是存在冗余?如果存在我们应该将其“瘦身”,然后保存得到的每一个解,最后求最小就可了。

代码

class Solution:
    def minWindow(self, s: str, t: str) -> str:
        hash_table = {}
        cnt = 0
        minLen = 1000000
        ans = ""
        left = 0
        for i in t:
            if i in hash_table.keys():
                hash_table[i] += 1
            else:
                hash_table[i] = 1
        
        for i in range(len(s)):  # i 相当于 tail,left 为 head
            if s[i] in hash_table.keys() and hash_table[s[i]] > 0:
                cnt += 1
                hash_table[s[i]] -= 1
            elif s[i] in hash_table.keys():
                hash_table[s[i]] -= 1
            
            while cnt == len(t):  # 当前得到的解是不是存在冗余
                if i - left < minLen:
                    minLen = i - left + 1
                    ans = s[left:i + 1]
                 
                if s[left] in hash_table.keys() and hash_table[s[left]] < 0:
                    hash_table[s[left]] += 1
                    left += 1
                elif s[left] not in hash_table.keys():
                    left += 1
                else:
                    hash_table[s[left]] += 1
                    left += 1
                    cnt -= 1
        return ans
                    
                
        
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值