您的位置:首页 > 其它

Minimum Window Substring 最小窗口覆盖所有字串

2015-09-28 11:30 330 查看


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).
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 empty string
""
.
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
class Solution {
public:
//双指针滑动 求最小窗口覆盖所有字串
//INT_MAX 2147483647 #include<limits.h>
    string minWindow(string s, string t) {
        
        int sLen=s.size();
        int tLen=t.size();
        int tHash[256],dp[256];
        memset(tHash,0,sizeof(tHash));//t字符的个数
        memset(dp,0,sizeof(dp));//计算字符数
        for(int i=0;i<tLen;i++){
            tHash[t[i]]++;
        }
        
        int count=0;
        int min=INT_MAX,start=0;
        int left=0,right=0;
        for(right=0;right<sLen;right++){
            if(tHash[s[right]]==0)//字串没有该字符
                continue;
            dp[s[right]]++;
            if(dp[s[right]]<=tHash[s[right]])//该字符增加一个
                count++;
                
            if(count==tLen){
                
                while(left<right){
                    if(tHash[s[left]]==0){//字串没有该字符
                		left++;
                		continue;
                	}
                    if(dp[s[left]]>tHash[s[left]]){
                        dp[s[left]]--;
                        left++;
                    }else{
                        break;
                    }
                }
                if(right-left+1<min){
                    min=right-left+1;
                    start=left;
                }
            }
        }
        
        if(min==INT_MAX)//未找到
            return "";
        //string res=s.substr(start,min); //三种赋值res的方法都可以
        //string res(s,start,min);
        string res;
        for(int i=start;i<start+min;i++)
            res+=s[i];
        return res;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: