LeetCode-Minimum Window Substring
2013-10-06 20:51
381 查看
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 =
T =
Minimum window is
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.
View Code
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.
class Solution { public: int sub(char c){ if(c>='a'&&c<='z'){ return c-'a'; } else if(c>='A'&&c<='Z') { return c-'A'+26; } else return -1; } string minWindow(string S, string T) { // Note: The Solution object is instantiated only once and is reused by each test case. vector<int> count,count2; count.resize(52,0); count2.resize(52,0); for(int i=0;i<T.length();i++){ int ind=sub(T[i]); if(ind!=-1)count[ind]++; } int dis=0; for(int i=0;i<52;i++){ dis+=count[i]; } int mins=-1,mine; int start=0,end=0; int ind=sub(S[end]); if(ind!=-1){ count2[ind]++; if(count2[ind]<=count[ind])dis--; } while(true){ if(dis!=0){ end++; if(end==S.length())break; int ind=sub(S[end]); if(ind!=-1){ count2[ind]++; if(count2[ind]<=count[ind])dis--; } } else{ if(mins==-1||end-start<mine-mins){ mins=start; mine=end; } int ind=sub(S[start]); if(ind!=-1){ count2[ind]--; if(count2[ind]<count[ind]){ dis++; } } start++; if(start>end)break; } } if(mins==-1)return ""; return S.substr(mins,mine-mins+1); } };
View Code
相关文章推荐
- [LeetCode][Java] Minimum Window Substring
- LeetCode76 Minimum Window Substring(两种解法)
- Leetcode: Minimum Window Substring
- LeetCode 76 Minimum Window Substring (尺取法 推荐)
- leetcode: Minimum Window Substring
- Leetcode: Minimum window substring
- [leetcode] 76 Minimum Window Substring
- leetcode Minimum Window Substring
- [LeetCode] Minimum Window Substring
- [leetcode]Minimum Window Substring
- [leetcode]Minimum Window Substring
- leetcode -- Minimum Window Substring
- LeetCode (Minimum Window Substring)
- LeetCode76——Minimum Window Substring
- [LeetCode]Minimum Window Substring
- LeetCode: Minimum Window Substring
- [LeetCode] Minimum Window Substring
- LeetCode-Minimum Window Substring
- LeetCode76 Minimum Window Substring(两种解法)
- LeetCode 76 Minimum Window Substring