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.
方法一:动态规划,但时间复杂度和空间复杂度太高
class Solution { public: string minWindow(string S, string T) { string result; if(S.length() == 0 || T.length() == 0) return result; if(S.length() < T.length()) return result; vector<int> layout('z'-'A'+1,0); for(int i = 0; i < T.length(); i++) layout[T[i]-'A']++; vector<vector<vector<int>>> record(S.length()+1,vector<vector<int>>(S.length()+1, vector<int>('z'-'A'+1,0))); for(int i = 1; i < S.length()+1; i++){ record[i][i][S[i-1]-'A']++; if(equal(layout.begin(),layout.end(),record[i][i].begin())){ result = S.substr(i-1,1); return result; } } for(int l = 2; l <= T.length(); l++){ for(int i = 1; i < S.length()+2-l; i++){ record[i][i+l-1] = record[i][i+l-2]; record[i][i+l-1][S[i+l-2]-'A']++; if(equal(layout.begin(),layout.end(),record[i][i+l-1].begin())){ result = S.substr(i-1,l); return result; } } } return result; } };
方法二:双指针,先移动win_end指针直到包含整个string T,再移动win_start指针缩小范围至一个极小window。继续上述操作,每次找到一个极小window,如果其小于当前最小window,更新最小window,直至win_end到达S末尾。
class Solution { public: string minWindow(string S, string T) { string result; if(S.length() == 0 || T.length() == 0) return result; if(S.length() < T.length()) return result; vector<int> expected_count(256,0); vector<int> appeared_count(256,0); for(int i = 0; i < T.length(); i++) expected_count[T[i]]++; int win_start = 0, win_end = 0; int min_win_size = INT_MAX, min_win_start = 0; int appeared = 0; for(win_end = 0; win_end < S.length(); win_end++){ if(expected_count[S[win_end]] > 0){ appeared_count[S[win_end]]++; if(appeared_count[S[win_end]] <= expected_count[S[win_end]]) appeared++; } if(appeared == T.length()){ while(appeared_count[S[win_start]] > expected_count[S[win_start]] || expected_count[S[win_start]] == 0){ appeared_count[S[win_start]]--; win_start++; } if(min_win_size > (win_end - win_start + 1)){ min_win_size = win_end - win_start + 1; min_win_start = win_start; } } } if(min_win_size == INT_MAX) return ""; return S.substr(min_win_start,min_win_size); } };