leetcode 76. Minimum Window Substring

本文介绍了一种使用双指针及映射表实现的高效算法,用于找出包含特定字符集的最小子串。通过示例解析了算法的具体实现步骤,并提供了完整的C++代码示例。

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

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

本题有难度。两个指针,map。
(1)i指针扫描,tmap[ s[i] ]=0 说明子串里刚好有足够个s[i],count++
(2)当count = T.size()时,l指针开始扫,扫到一个就tmap[s[i]]++,因为l是子串左指针,说明缺失一个s[i],开始缺失就是子串开始的位置,更新长度

class Solution {
public:
    string minWindow(string s, string t) 
    {
       map<char,int> tmap;
       for (int i = 0; i < t.size(); i++)
            tmap[t[i]]++;
       
       int count = 0;
       int l = 0;
       int left;//存目标子串开始位置
       int length = s.size() + 1;//目标子串长度
       for (int i = 0; i < s.size(); i++)
       {
            if(tmap.find(s[i]) != tmap.end())//子串开头肯定是在tmap里面
            {
                tmap[s[i]]--;
                if (tmap[s[i]] >= 0)    //这一步 >= 很关键。因为t中可能有重复的字母。 不能是 ==
                    count++;            // >= 0 说明没有找多,因为找多了就 < 0
               
                while (count == t.size())
                {
                    if (tmap.find(s[l]) != tmap.end())
                    {
                        tmap[s[l]]++;
                        if (tmap[s[l]] > 0)   // > 0代表开始缺失,说明找到了子串的开头.如果找到了还是 <= 0 那就说明本来就是多找的,根本不缺。
                        {  
                            count--;
                            if (i-l+1 < length)
                            {
                                length = i-l+1; 
                                left = l;  
                            }    
                        }
                    }
                    l++;    //子串左边界++
                }
            }
        }
        return (length == s.size() + 1) ? "" : s.substr(left, length);  
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值