【ATT】Minimum Window Substring

O(n)的解法。

[i,j]维护一个window,当cnt==tlen时表示这是一个valid window.  Increment cnt by one if hasFound[x] is less than or equal to needToFind[x]. Why? When the constraint is met (that is, count equals to T's size), we immediately advance begin pointer as far right as possible while maintaining the constraint.

needed[] stores the total count of characters in T.

Founded[] stores the total count of character met in the cur mindow.

 

 

cnt的技术

    string minWindow(string S, string T) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(S.empty()||T.empty())
            return "";
    
        int needed[256] = {0};
        int found[256] = {0};
        //precompute
        int i,j;
        for(i=0;i<T.size();i++)
            needed[T[i]]++;
            
        i = j = 0;
        int slen = S.size();
        int tlen = T.size();
        int min_window = INT_MAX;
        int startIndex=-1;
        int cnt = 0;
        while(j<slen)
        {
            if(needed[S[j]]==0)  //skip the character not in T
            {
                ++j;
                continue;
            }
            found[S[j]]++;
            if(found[S[j]]<=needed[S[j]]) //<= increment cnt
                cnt++;
            
            if(cnt==tlen) //met a valid window
            {
                
                while(needed[S[i]]==0||found[S[i]]>needed[S[i]]) // advance the begin pointer as far as possbile
                {
                    if(found[S[i]]>needed[S[i]])
                        found[S[i]]--;
                    i++;
                }
                if(j-i+1<min_window)  //update
                {
                    min_window = j-i+1;
                    startIndex = i;
                }
            }
            ++j;
        }
        
        if(startIndex==-1)
            return "";
        else
            return S.substr(startIndex,min_window);
        
        
    }

  

posted @ 2013-10-26 13:46  summer_zhou  阅读(212)  评论(0编辑  收藏  举报