leetcode 76 Minimum Window Substring

本文介绍了一种在字符串S中寻找包含字符串T所有字符的最短子串的高效算法,复杂度为O(n)。通过使用双指针技术和哈希表来实现,详细解释了算法的实现过程,并给出了具体的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 emtpy string “”.

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

Hide Tags Hash Table Two Pointers String
Hide Similar Problems (H) Substring with Concatenation of All Words (M) Minimum Size Subarray Sum (H) Sliding Window Maximum

代码

class Solution {
public:
    string minWindow(string s, string t) {
        if(s.length()<t.length()){
            return "";
        }

        //t中可能存在重复字符串,要统计每个字符的数目
        map<char,int> needToFind;
        map<char,int> hasFound;
        for(int i=0;i<t.length();i++){
            if(needToFind.find(t[i])!=needToFind.end()){
                needToFind[t[i]]+=1;
            }else{
                needToFind[t[i]]=1;
                hasFound[t[i]]=0;
            }
        }

        char c;
        string ret="";
        bool retValid=false;
        for(int count=0,begin=0,end=0;end<s.size();end++){
            c=s[end];
            //对s,只处理t中存在的字符,其他的字符直接忽略
            if(needToFind.find(c)!=needToFind.end()){
                //处理当前字符,更新count和hasFound
                if(hasFound[c]<needToFind[c]){
                    count++;
                }
                hasFound[c]++;
                //begin-end包含全部t的字符
                if(count==t.length()){
                    //先扔掉begin-end中:begin处,不是t中的和hasFound》needTofind
                    while(needToFind.find(s[begin])==needToFind.end() || hasFound[s[begin]]>needToFind[s[begin]]){
                        if(needToFind.find(s[begin])!=needToFind.end() && hasFound[s[begin]]>needToFind[s[begin]]){
                            hasFound[s[begin]]--;
                        }
                        begin++;
                    }
                    //检查这个子串是否是最短的
                    if(retValid==false){
                        retValid=true;
                        ret=s.substr(begin,end-begin+1);
                    }else if(end-begin+1 < ret.length()){
                        ret=s.substr(begin,end-begin+1);
                    }
                }
            }
        }
        return ret;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值