[NeetCode 150] Minimum Window With Characters

Minimum Window With Characters

Given two strings s and t, return the shortest substring of s such that every character in t, including duplicates, is present in the substring. If such a substring does not exist, return an empty string “”.

You may assume that the correct output is always unique.

Example 1:

Input: s = "OUZODYXAZV", t = "XYZ"

Output: "YXAZ"

Explanation: “YXAZ” is the shortest substring that includes “X”, “Y”, and “Z” from string t.

Example 2:

Input: s = "xyz", t = "xyz"

Output: "xyz"

Example 3:

Input: s = "x", t = "xy"

Output: ""

Constraints:

1 <= s.length <= 1000
1 <= t.length <= 1000

s and t consist of uppercase and lowercase English letters.

Solution

It is apparently a sliding window question and we can easily count the number of characters in the window. So, the key problem becomes to check whether the current substring satisfies the requirement.

In fact, we will only add or remove on character at once, which means there will only be at most 1 kind of character satisfies or dissatisfies the requirements. Therefore, we can maintain the number of requirements that has been satisfied and change this number will adding/removing characters.

Code

class Solution:
    def minWindow(self, s: str, t: str) -> str:
        t_stat = {}
        win_stat = {}
        for c in range(ord('A'), ord('Z')+1):
            t_stat[chr(c)] = 0
            win_stat[chr(c)] = 0
        for c in range(ord('a'), ord('z')+1):
            t_stat[chr(c)] = 0
            win_stat[chr(c)] = 0
        satis_num = 0
        for c in t:
            t_stat[c] += 1
        for key in t_stat.keys():
            if t_stat[key] <= win_stat[key]:
                satis_num += 1

        le = 0
        ans_le, ans_ri = -1001, -1
        for ri in range(len(s)):
            win_stat[s[ri]] += 1
            if win_stat[s[ri]] == t_stat[s[ri]]:
                satis_num += 1
            print(satis_num)
            print(le, ri)
            while le <= ri and satis_num >= 52:
                if ri-le+1 < ans_ri-ans_le+1:
                    ans_le = le
                    ans_ri = ri
                if win_stat[s[le]] == t_stat[s[le]]:
                    satis_num -= 1
                win_stat[s[le]] -= 1
                le += 1
        if ans_le < 0:
            return ''
        return s[ans_le: ans_ri+1]
                

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ShadyPi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值