關於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 empty string “”.

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

首先,看完這題我首先想到用一個數組來標記

int temp[128]={0};//因爲字符最大不會大於127,所以如此

接着,讀入第二個串並記錄,每個字符出現次數。
然後,從頭開始當字符記錄不爲0

while(end<s.size()){
        if(temp[s[end]]!=0){
        temp[s[end]]--;//當所需子串多次出現 
        if(temp[s[end]]>=0)
        total--;
        if(temp[s[end]]==0){
        temp[s[end]]=-1;//用於標識該字符是否出現在子串。 
} 
end++;
}
else{
end++;
}

其中,最後是縮減子串,已獲得更多解,以求最優解。

while(total==0){
             if(end-begin<ans) {
                ans=(end-begin) ;
                first=begin;
             }//存在更優解 

             if(temp[s[begin]]==-1) {
                total++;
                temp[s[begin]]=1;
             }
             if(temp[s[begin]]<-1)
             temp[s[begin]]++;
             begin++;//縮小區間 
            }
下面是完整代碼:
string minWindow(string s, string t) {
        int temp[128]={0};
        for(int i=0;i<t.length();i++) temp[t[i]]++;
        int total=t.size(), begin=0, end=0, ans=INT_MAX, first=0;
        while(end<s.size()){
            if(temp[s[end]]!=0){
                temp[s[end]]--;//當所需子串多次出現 
            if(temp[s[end]]>=0)
                total--;
                if( temp[s[end]]==0){
                        temp[s[end]]=-1;//用於標識該字符是否出現在子串。 
                } 
                end++;
            }
            else{
                end++;
            }

            while(total==0){
             if(end-begin<ans) {
                ans=(end-begin) ;
                first=begin;
             }//存在更優解 

             if(temp[s[begin]]==-1) {
                total++;
                temp[s[begin]]=1;
             }
             if(temp[s[begin]]<-1)
             temp[s[begin]]++;
             begin++;//縮小區間 
            }

        }

        return ans==INT_MAX? "":s.substr(first, ans);
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章