leetcode Minimum Window Substring答案解析

本文介绍了一种在字符串S中找到包含字符串T所有字符的最短子串的方法,复杂度为O(n)。通过使用两个索引表来跟踪T中字符的出现次数和在S中已查找到的字符次数,实现高效搜索。

摘要生成于 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 empty string "".

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

要求查找S中包含T中所有字母的最短子串

解题思路:

建立两个索引表,分别用来存储T中每个字母出现的次数(即needfound)和已经查找过的在start到end中间的各字母的出现次数


class Solution {
public:
    string minWindow(string s, string t) {
        vector<int> found(128,0);
        vector<int> tt(128,0);
        for(int i=0;i<t.length();i++)
            tt[t[i]]++;
        found[s[0]]++;
        int count=t.length(),start=0,end=0,ans=s.length()+1,minbegin=0;
        if(tt[s[0]]>=found[s[0]])
            count--;
        while(end<s.length()){
            if(count==0){
                while(found[s[start]]>tt[s[start]]){
                    found[s[start]]--;
                    start++;
                }
                if(end-start+1<ans){
                    ans=end-start+1;
                    minbegin=start;
                }
            }
            end++;
            found[s[end]]++;
            if(tt[s[end]]>=found[s[end]])
                count--;
        }
        if(ans>s.length())
            return "";
        return s.substr(minbegin,ans);
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值