1. 程式人生 > >[LeetCode] Minimum Window Substring

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

這道題的關鍵是如何記錄到當前位置各個有效字元出現的次數,要以O(1)的速度來獲取某個字元的出現次數,必須以空間換取時間,我的想法有兩個,一個是使用陣列記錄,另外一個就是使用HashMap來儲存,當然,暫時使用的是陣列,同時,再掃描資料的過程中統計有效次數有多少,依次有效的字元是出現再目標子字元中的,並且從當前開始字元到目前為止出現次數不大於目標字串中該字元的出現次數。當有效次數達到了目標字元的總數之後,再從開始的字元開始掃描一遍以便獲取開始的位置。再次過程中我們還要對現有的統計必要的更改。

class MinWindow
{
    
private:
    static const int CHARCOUNT = 256;
    int countN[CHARCOUNT],countT[CHARCOUNT];
    int usefulCount;
public:
    string minWindow(string S, string T) {
        usefulCount = 0;
        memset(countN,0, sizeof(countN));
        memset(countT,0, sizeof(countT));
        for(int i=0;i<T.length();i++)
        {
            countT[T[i]-'A']++;
        }
        int retBegin  = -1 ,retEnd = -1;
        int minLength = INT_MAX;
        int begin = 0,i=0;
        for(i=0;i<S.length();i++)
        {
            char c = S[i];
            if(countT[c-'A']==0)
                continue;
            if(countN[c-'A']<countT[c-'A'])
            {
                countN[c-'A']++;
                usefulCount++;
            }
            else
                countN[c-'A']++;
            if(usefulCount==T.length())
            {
                for(int k=begin;k<=
                    i;k++)
                {
                    char ic = S[k];
                    if(countT[ic-'A']==0)
                        continue;
                    if(countN[ic-'A']>countT[ic-'A'])
                        countN[ic-'A']--;
                    else if(countN[ic-'A']==countT[ic-'A'])
                    {
                        countN[ic-'A']--;
                        usefulCount--;
                        begin = k;
                        break;
                    }
                    
                }
                if(i-begin<minLength)
                {
                    retBegin = begin;
                    retEnd = i;
                    minLength = i-begin;
                }
                begin++;
                
            }
        }
        return retBegin == -1?"":S.substr(retBegin,retEnd-retBegin+1);
    }
};