LeetCode-76-Minimum Window Substring

本文详细解析了如何使用滑动窗口算法寻找包含特定字符的最小子串,通过具体实例展示了算法的设计与实现过程。

摘要生成于 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).

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.

解题思路:子字符串问题,可以采用强大的滑动窗口方法解决。首先用map对字符串进行映射,并用两个指针分别指向窗口左边和右边,通过不断的滑动两个指针实现对窗口内字符的操作。

    string minWindow(string s, string t) {
        string res = "";
        unordered_map<char,int> map;
        for(char c:t) map[c]++;
        int left=0;
        int right = 0;
        int distance = INT_MAX;
        int count = t.size();
        int head = 0;
        while(right < s.size()){
            if(map[s[right++]]-- >0) count--;
            while(count==0){
                if(right-left< distance){
                    head = left;
                    distance = right-head;
                }
                if(map[s[left++]]++ ==0) count++;
            }
        }
        return distance==INT_MAX?"":s.substr(head,distance);
    }

 

转载于:https://www.cnblogs.com/nobodywang/p/10372839.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值