LeetCode OJ:Minimum Window Substring

来源:互联网 发布:java json tobean 编辑:程序博客网 时间:2024/05/17 06:43

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 emtpy string "".

If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.


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

class Solution {public:    string minWindow(string S, string T) {        if(S.empty()||T.empty())return "";        int minSize=INT_MAX;        int minStart;        int flag[256]={0};        int count[256]={0};        for(int i=0;i<T.size();i++){            flag[T[i]]++;            count[T[i]]++;        }        int cnt=T.size();        int start=0;        for(int end=0;end<S.size();end++){            if(flag[S[end]]){                count[S[end]]--;                if(count[S[end]]>=0)cnt--;            }            if(cnt==0){                for(;start<=end;start++){                    if(flag[S[start]]){                        if(count[S[start]]<0)count[S[start]]++;                        else break;                    }                }                if(minSize>end-start+1){                    minSize=end-start+1;                    minStart=start;                }            }        }        if(minSize==INT_MAX)return "";        return S.substr(minStart,minSize);    }};


0 0
原创粉丝点击