[leetcode] Minimum Window Substring

来源:互联网 发布:玩天龙八部网络延迟 编辑:程序博客网 时间:2024/05/01 11:13

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.

原文链接:http://blog.csdn.net/jellyyin/article/details/10313827

思路:双指针,动态维护一个区间。尾指针不断往后扫,当扫到有一个窗口包含了所有T的字符后,然后再收缩头指针,直到不能再收缩为止。最后记录所有可能的情况中窗口最小的

代码:

class Solution {public:    string minWindow(string S, string T) {        int slen=S.size();        int tlen=T.size();        if(tlen>slen || tlen==0 || slen==0) return "";        int needFind[256]={0};        int hasFind[256]={0};        for(int i=0;i<tlen;i++){            needFind[T[i]]++;        }        int minLength=INT_MAX;        int minbegin=0;        int minend=slen-1;        int begin=0;        int end=0;        for(int count=0;end<slen;end++){            if(needFind[S[end]]==0) continue;            hasFind[S[end]]++;            if(hasFind[S[end]]<=needFind[S[end]]) count++;            if(count==tlen){                while(begin<end){                    if(needFind[S[begin]]==0){                        begin++;                        continue;                    }                    if(hasFind[S[begin]]>needFind[S[begin]]){                        hasFind[S[begin]]--;                        begin++;                        continue;                    }                    else                        break;                }                int tempLength=end-begin+1;                if(tempLength<minLength){                    minbegin=begin;                    minend=end;                    minLength=tempLength;                }            }        }        if(minLength==INT_MAX) return "";        return S.substr(minbegin,minLength);    }};


0 0
原创粉丝点击