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).

For example,
S = “ADOBECODEBANC”
T = “ABC”
Minimum window is “BANC”.

Note:
If there is no such window in S that covers all characters in T, return the empty string “”.

If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.

思路:哈希表法。这里用两个数组tm和sm代替哈希表,首先统计T中每个字母的个数(可能一个字母有多个),然后开始滑动窗口,左端点起点为0,遍历右端点,如果遇到S中有T中的字母且个数不超过T中该字母的个数,则计数加1,直到计数达到T中字母个数,即S中窗口包含T为止,如果该窗口小于最小窗口长度,则更新最小窗口,同时左端点前移,如果左端点包含T中字母,则减去一个S中该字母的个数,若此时所需T中该字母个数不够,则计数减1,继续前移右窗口,滑动窗口直到结束。

class Solution {
public:
    string minWindow(string S, string T) {
        if (T.size()>S.size()) return "";
        string res="";
        int left=0,count=0,minLen=S.size()+1;
        int tm[256]={0},sm[256]={0};
        for(int i=0;i<T.size();i++) tm[T[i]]++;
        for(int right=0;right<S.size();right++){
            if(tm[S[right]]){
                sm[S[right]]++;
                if(sm[S[right]]<=tm[S[right]]) count++;
                while(count==T.size()){
                    if(right-left+1<minLen){
                        minLen=right-left+1;
                        res=S.substr(left,minLen);
                    }
                    if(tm[S[left]]){
                        sm[S[left]]--;
                        if(sm[S[left]]<tm[S[left]]) count--;
                    }
                    left++;
                }
            }
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值