【LeetCode】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

思路:滑动窗口,包含子串(顺序任意)的最小窗口,先把子串转为map来表示,然后用两指针,start和j,每次只要窗口内子串数不为0就递增j,每次遍历都把map计数器--,只有>=0说明该元素是子串中的(不是重复的)把m--(这里用m是否为0来更新ans,0说明窗口已经包含了子串),m=0递增start并map对start的计数++,>0说明一定是子串中(不重复)只有重复或不是子串的才会=0或者小于0,根据这两条来移动指针。

class Solution {
public:
    string minWindow(string s, string t) {
        int n=s.size(),m=t.size();
        vector<int> h(130);
        for(auto c:t) h[c]++;
        int i=0,start=0,len=INT_MAX,cur=0;
        while(i<=n&&start<n){
            if(m){
                if(i==n) break;
                h[s[i]]--;
                if(h[s[i]]>=0) m--;
                i++;
            }else{
                if(len>i-start){
                    len=i-start;cur=start;
                }

                h[s[start]]++;
                if(h[s[start]]>0) m++;
                start++;
            }

        }
        return len==INT_MAX?"":s.substr(cur,len);
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值