Thursday, January 23, 2014

[Leetcode] 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.

Algorithm:
1. Need 2 pointers begin and end to update the window.
2. Need 2 hashtable to maintain: NeedToFind[256] and HasFound[256]. NTF is the chars occurred in the second string. HFD is the chars already found.
3. Use count to update the validate chars in [begin, end]. When count == T.length(), current window is a validate window.
4. Use minlen and minstart to maintain the minimum window. use curlen to see the current window len.
5. Things easy to be wrong: 
    always keep HFD and NTF as zero for the chars not in T; 
    update the HFD first and then see from begin to delete;
    if minlen is never updated, then return "".(because not a window is validated)
My code:
string minWindow(string S, string T) {
        if(S.length() < T.length()) return "";
        //initialize NTH
        int NTF[256] = {0};
        for(int i = 0; i < T.length(); ++i){
            NTF[T[i]]++;
        }
        int HFD[256] = {0};
        int begin = 0;
        int end = 0;
        int minlen = INT_MAX;
        int minstart = begin;
        int curlen = 0;
        int count = 0;
        for(end = 0; end < S.length(); ++end){
            if(NTF[S[end]] == 0) continue;
            else {
                HFD[S[end]]++;
                if(HFD[S[end]] <= NTF[S[end]]){
                    count++;
                }
                if(count == T.length()){
                    while(HFD[S[begin]] > NTF[S[begin]] || NTF[S[begin]] == 0){
                        if(NTF[S[begin]] != 0){
                            HFD[S[begin]]--;
                        }
                        begin++;
                    }
                    curlen = end - begin + 1;
                    if(curlen < minlen){
                        minlen = curlen;
                        minstart = begin;
                    }
                }
            }
           
        }
        if(minlen == INT_MAX) minlen = 0;
        return S.substr(minstart, minlen);
    }

No comments:

Post a Comment