leetcode 76 Minimum Window Substring

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

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;
    }
};
### LeetCode76题 Python 解法 LeetCode76题名为 **Minimum Window Substring**,目标是在字符串 `s` 中找到包含字符串 `t` 的所有字符的最小窗口。以下是基于滑动窗口算法实现的一个高效解决方案。 #### 滑动窗口算法思路 通过维护两个指针(左指针和右指针),构建一个动态调整大小的窗口来覆盖所需的目标子串。具体步骤包括初始化计数器、扩展窗口直到满足条件以及收缩窗口优化结果。 下面是完整的代码实现: ```python from collections import Counter class Solution: def minWindow(self, s: str, t: str) -> str: if not s or not t: return "" dict_t = Counter(t) # 统计目标字符串中的字符频率 required = len(dict_t) # 需要匹配的不同字符数量 l, r = 0, 0 # 左右指针 formed = 0 # 当前窗口中已经匹配到的不同字符数量 window_counts = {} # 记录当前窗口内的字符频率 ans = float("inf"), None, None # 存储最终答案 (长度, 起始索引, 结束索引) while r < len(s): char = s[r] window_counts[char] = window_counts.get(char, 0) + 1 if char in dict_t and window_counts[char] == dict_t[char]: formed += 1 while l <= r and formed == required: char = s[l] if r - l + 1 < ans[0]: # 更新最优解 ans = (r - l + 1, l, r) window_counts[char] -= 1 if char in dict_t and window_counts[char] < dict_t[char]: formed -= 1 l += 1 # 收缩窗口 r += 1 # 扩展窗口 return "" if ans[0] == float("inf") else s[ans[1]:ans[2]+1] ``` 上述方法的时间复杂度为 \(O(|S| + |T|)\),其中 \(|S|\) 和 \(|T|\) 分别表示输入字符串 `s` 和 `t` 的长度[^5]。 --- #### 关键点解析 1. 使用 `Counter` 来统计目标字符串 `t` 中各字符的数量。 2. 利用双指针技术逐步扩大和缩小窗口范围,确保窗口始终能够覆盖所需的全部字符。 3. 动态更新窗口状态并记录最短的有效区间。 此方案不仅效率高而且易于理解,在处理大规模数据时表现尤为突出。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值