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.

思路:采用双指针记录窗口的左右边界,通过数组记录窗口字符非窗口字符的数量是否大于或小于0,判断移动双指针策略。

class Solution {
public:
    string minWindow(string s, string t) {
        int count[128]={0};
        for(auto i : t) count[i]++; //记录窗口各字符数量
        int strlen=0,minlen=s.size();
        string res;
        
        for(int l=0,r=0; r< s.size(); r++){
            //若是窗口字符 +1,否则-1
            if(--count[s[r]] >= 0 )  strlen++; //每匹配一个窗口字符,记录一下
            while(strlen == t.size()){  //窗口字符全部匹配成功,定位窗口位置
                if(minlen >= (r-l+1)){
                    minlen = r-l+1;
                    res = s.substr(l,minlen);
                }
                if(++count[s[l++]] >0) strlen--; //抛弃一个窗口字符,则匹配长度-1,不是窗口字符不受影响
            }
        }
        return res;
        
    }
};

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值