LeetCode 76. Minimum Window Substring

76. Minimum Window Substring

Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).

Example:

Input: S = “ADOBECODEBANC”, T = “ABC”
Output: “BANC”
Note:

If there is no such window in S that covers all characters in T, return the empty string “”.
If there is such window, you are guaranteed that there will always be only one unique minimum window in S.

Approach

题目大意:找到长度最小的序列并且包含T中所有的字母
解题思路:用的还是滑动窗口的思想,关键主要是能找到一个标志用来判断窗口是否满足要求,然后进行滑动。所以窗口滑动的标志就是这个窗口已包含了t中的所有字母,然后就可以滑动了。

Code

class Solution {
public:
    string minWindow(string s, string t) {
        vector<int> expects(256, 0), apper(256, 0);
        for (const char &st:t)expects[st]++;
        int left = 0, width = 0, cnt = 0, mleft = 0;
        for (int right = 0; right < s.size(); right++) {
            if (expects[s[right]]) {
                apper[s[right]]++;
                if (apper[s[right]] <= expects[s[right]]) {
                    ++cnt;
                }
            }
            if (cnt == t.size()) {
                while (expects[s[left]] == 0 || apper[s[left]] > expects[s[left]]) {
                    apper[s[left]]--;
                    left++;
                }
                if (width == 0 || width > right - left + 1) {
                    width = right - left + 1;
                    mleft = left;
                }
            }
        }
        if (width == 0)return "";
        return s.substr(mleft, width);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值