[leetcode]76. Minimum Window Substring

本文详细解析了如何寻找字符串S中包含字符串T所有字符的最小子串,并提供了高效的算法实现。通过维护两个索引Start和End,文章逐步介绍了算法的逻辑流程与优化策略。

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

链接:https://leetcode.com/problems/minimum-window-substring/description/

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

Example:

Input: S = "ADOBECODEBANC", T = "ABC"
Output: "BANC"

Note:

  • If there is no such window in S that covers all characters in T, return the empty string "".
  • If there is such window, you are guaranteed that there will always be only one unique minimum window in S.

思路:

思路:

维护两个索引Start 和 End(初值都为0),分别标识 子串W(这里表示Window)的开始位置和结束位置。

下面关键就是判断何时这两个索引要变化。

1.首先如果没有找到map中的单词,End++,继续往后找。

2.如果map中的字母还没找完,且找到了当前字母,则map中当前单词对应的value--(表示找到一个)。

3.当然可能有重复字母,即value减为负了,这样找出来的window包含多余重复字母肯定不是最优,所以我们要记录找到字母个数。

4.一旦找满单词,这个时候Start到End的位置肯定是包含目标T串所有字符的子串W(即Window)

5.但是这个window不是最优的,我们要对start++,排除不在map中的字符(其实就是让Start越过步骤1中跳过的字符),缩小window大小

6.还有需要优化的地方,就是当window中出现重复的字符,这时,map中该字符的value为负了,我们可以向前移动start。

关于第6点,比如说:

母串ABCDDDDDDDA

目标串ABC

那么当End移动到最后一个A时,Start只能停在第一个A处(为了保证Window中包含ABC三个字母)

而当End移动到最后一个A时,此时Window中多一个A(Map中A的值减为负了),这个时候Start就可以往前移动一下,做一步优化。

根据上述6点,代码就很容易了:

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

        unordered_map<char,int> map;
        int count = t.length();
        int start = 0, end = 0, minLen = INT_MAX, startIndex = 0;
        /// UPVOTE !
        for (char c : t) {
            if(map.find(c) == map.end()) {
                map[c]=1;
            }
            else {
                 map[c]++;
            }
           
        }

        while (end < s.length()) {
            if (map[s[end++]]-- > 0) {
                count--;
            }

            while (count == 0) {
                if (end - start < minLen) {
                    startIndex = start;
                    minLen = end - start;
                }
                if(map.count(s[start])) {
                    if (map[s[start++]]++ == 0) {
                        count++;
                    }
                }
                
            }
        }

        return minLen == INT_MAX ? "" : s.substr(startIndex, minLen);
    }
};

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值