Skip to content

Instantly share code, notes, and snippets.

@superlayone
Last active August 29, 2015 13:57
Show Gist options
  • Select an option

  • Save superlayone/9829369 to your computer and use it in GitHub Desktop.

Select an option

Save superlayone/9829369 to your computer and use it in GitHub Desktop.
这是宿舍人面试豌豆荚的一道题,正好没做过,拿来做做

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.

思路

利用start和end两个指针,动态维护一个区间,

首先尾指针不断往后扫,当扫到有一个包含了所有 T 的字符后的位置处停止,

然后再收缩头指针,直到不能再收缩为止。

最后选择出所有可能的情况中窗口最小的

	class Solution {
	public:
	    string minWindow(string S, string T) {
	        if(S.size() == 0){
	            return "";
	        }
	        if(S.size() < T.size()){
	            return "";
	        }
	        vector<int> countS(256,0);
	        vector<int> countT(256,0);
	        
	        //count for T
	        for(auto i=0;i<T.size();i++){
	            countT[T[i]]++;
	        }
	        //min width
	        int minWidth = INT_MAX;
	        //min start
	        int minStart=0;
	        int start=0;
	        //if contain all T elements
	        int containT=0;
	        for(auto end=0;end<S.size();end++){
	            if(countT[S[end]]>0){
	                countS[S[end]]++;
	                if(countS[S[end]] <= countT[S[end]]){
	                    containT++;
	                }
	            }
	            //contain all T
	            if(containT == T.size()){
	                while(countS[S[start]] > countT[S[start]] || countT[S[start]] == 0){
	                    countS[S[start]]--;
	                    start++;
	                }
	                if(minWidth > (end - start)+1){
	                    minWidth = end - start + 1;
	                    minStart = start;
	                }
	            }
	        }
	        if(minWidth == INT_MAX){
	            return "";
	        }else{
	            return S.substr(minStart,minWidth);
	        }
	    }
	};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment