字符串最小窗口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).

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);
        
        
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值