leetcode 76: Minimum Window Substring

本文介绍了一种寻找字符串中包含所有目标字符的最小子串的高效算法。通过使用滑动窗口和计数器来动态调整搜索范围,实现快速定位。适用于需要从大量数据中筛选特定模式的应用场景。

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

class Solution {
public:
    string minWindow(string s, string t) {
        int slen=s.length();
        int tlen=t.length();
        int need[128]={INT_MIN};
        for(int i=0;i<tlen;i++)
            need[t[i]]=need[t[i]]==INT_MIN?1:need[t[i]]+1;
        int start=0,end=0,count=0,min_len=INT_MAX,min_idx=0;
        for(;end<slen;end++)
        {
            if(need[s[end]]>0)//needed by t
            {
                need[s[end]]--;
                count++;
            }
            else if(need[s[end]]!=INT_MIN)needed but the number is enough
                need[s[end]]--;
            if(count==tlen)
            {
                while(need[s[start]]<0)//find the non-redundant start
                {
                    if(need[s[start]]!=INT_MIN)
                        ++need[s[start++]];
                    else
                        start++;
                }
                if(end-start+1<min_len)//update the min
                {
                    min_len=end-start+1;
                    min_idx=start;
                }
                need[s[start]]++;
                start++;
                count--;
            }
        }
        return min_len==INT_MAX?"":s.substr(min_idx,min_len);
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值