字符串最小窗口Minimum Window Substring

本文介绍了一种在字符串S中寻找包含字符串T所有字符的最短子串的算法,复杂度为O(n)。通过使用滑动窗口和哈希映射的方式实现高效查找,文章详细解释了算法的实现思路与步骤。
摘要由CSDN通过智能技术生成

 


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.

 

 

 

class Solution {

public:
    string minWindow(string source, string target) {
        
        // write your code here
        if(target.size()==0||source.size()==0){
            return "";
        }
        // 1 先统计出target目标字符的个数的统计 
        //2  遍历 元字符串 也进行 字符统计  start end 一个符合子串的
        map<char,int> mtar,msrc;
        int start=0,end=-1,begin;
        int found=0; // 统计发现的次数
        
        int length=999; // 每次比较子串的长度
        
        for(int i=0;i<target.size();++i){
            mtar[target[i]]++;
        }
        
        for(int i=0;i<source.size();++i){
            msrc[source[i]]++;
            if(msrc[source[i]]<=mtar[source[i]]){
                found++; // 发现一个目标字符就加一
            }
            if(found==target.size()){ //found=len 说明找到一个符合的子串
                
                // 计算开始的位置  结尾的位置现在以i结尾
                while(start<i&&msrc[source[start]]>mtar[source[start]]){
                    msrc[source[start]]--; // 先把start位置减一 
                    
                    start++; // 开始位置 
                
                }
                if(i-start<length){ // 最小长度
                    begin=start;
                    end=i;
                    length=i-start;
                }
                
                // 将头一个字符的统计减一  往后移动
                msrc[source[start]]--;
                found--;
                
                start++; //开始位置也加1;
            }
        }


        return end==-1?"":source.substr(begin,length+1);
        
        
    }
};

滑动窗口是一种常用的算法技巧,可以用于解决一类问题,其中包括一些LeetCode上的题目。通过维护一个窗口,我们可以在线性时间内解决一些需要处理连续子数组或子字符串的问题。以下是一些常见的滑动窗口问题: 1. 最小覆盖子串(Minimum Window Substring):给定一个字符串S和一个字符串T,在S中找出包含T所有字符的最小子串。 2. 字符串的排列(Permutation in String):给定两个字符串s1和s2,判断s2是否包含s1的排列。 3. 找到字符串中所有字母异位词(Find All Anagrams in a String):给定一个字符串s和一个非空字符串p,找到s中所有是p的字母异位词的子串。 4. 替换后的最长重复字符(Longest Repeating Character Replacement):给定一个只包含大写英文字母的字符串s,你可以将一个字母替换成任意其他字母,使得包含重复字母的最长子串的长度最大化。 5. 至多包含两个不同字符的最长子串(Longest Substring with At Most Two Distinct Characters):给定一个字符串s,找出至多包含两个不同字符的最长子串的长度。 以上只是几个例子,滑动窗口可以应用于更多类型的问题。在解决这些问题时,我们通常使用两个指针来表示窗口的左右边界,并根据具体问题的要求移动窗口。在每次移动窗口时,我们可以更新窗口的状态,例如统计字符出现次数、判断窗口是否满足条件等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值