[LeetCode]Minimum Window Substring

本文介绍了一种在字符串S中寻找包含字符串T所有字符的最短子串的算法,复杂度为O(n)。通过使用双指针技术和哈希表维护匹配字符的状态,实现了高效的子串查找。

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.

双指针,用hash来维护匹配的字符。然后伸缩前指针,注意收缩的原则。如果出现新的数字可以替代现在的前面数字就收缩解集。

class Solution {
public:
    string minWindow(string s, string t) {
        int min = INT_MAX;
        int subs = 0;
        vector<int> appearedNum(300,0);
        vector<int> expectNum(300,0);
        for(int i=0; i<t.length(); ++i){
            expectNum[t[i]]++;
        }
        int start=0,end = 0;//初始化
        int count = 0;
        for(end=0; end<s.length(); ++end){
            if(expectNum[s[end]]>0){
                appearedNum[s[end]]++;
                if(appearedNum[s[end]]<=expectNum[s[end]])
                    count++;
            }//统计出现数字
            if(count == t.length()){//出现可收缩解的情况就收缩头指针
                while(appearedNum[s[start]]>expectNum[s[start]]||expectNum[s[start]]==0){
                    appearedNum[s[start]]--;
                    start++;
                }
                if(min>end-start+1){
                    min = end-start+1;
                    subs = start;
                }
            }
        }
        
        if(count<t.length()) return "";
        else    return s.substr(subs,min);
    }
};



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值