[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.
Hash Table Two Pointers String
思路:
双指针,动态维护一个区间。尾指针不断往后扫,当扫到有一个窗口包含了所有 T 的字符后,
然后再收缩头指针,直到不能再收缩为止。最后记录所有可能的情况中窗口最小的
时间复杂度 O(n),空间复杂度 O(1)
class Solution { public: string minWindow(string S, string T) { if(S.empty() || T.empty() || S.size() < T.size()) return string(); vector<int> expect(256, 0); vector<int> appear(256, 0); for(int i = 0; i < T.size(); i++) { expect[T[i]] ++; } int minWidth = INT_MAX, min_start = 0; // int win_start = 0; int appearCharCnt = 0; for(int win_end = 0; win_end < S.size(); win_end++) { if(expect[S[win_end]] > 0) // this char is part of T { appear[S[win_end]]++; if(appear[S[win_end]] <= expect[S[win_end]]) appearCharCnt ++; } //cout << "appearCharCnt\t" <<appearCharCnt<< endl; if(appearCharCnt == T.size()) { // shrink the start while (appear[S[win_start]] > expect[S[win_start]] || expect[S[win_start]] == 0) { appear[S[win_start]]--; win_start++; } if ((win_end - win_start + 1) < minWidth) { minWidth = win_end - win_start + 1; min_start = win_start; //cout << "min_start\t" <<min_start << endl; //cout << "min_width\t" <<minWidth<< endl; } } } if (minWidth == INT_MAX) return ""; else return S.substr(min_start, minWidth); } };
精简一下条件判断
class Solution { public: string minWindow(string S, string T) { if(S.empty() || T.empty() || S.size() < T.size()) return string(); vector<int> expect(256, 0); vector<int> appear(256, 0); for(int i = 0; i < T.size(); i++) { expect[T[i]] ++; } int minWidth = INT_MAX, min_start = 0; int win_start = 0; int appearCharCnt = 0; for(int win_end = 0; win_end < S.size(); win_end++) { appear[S[win_end]]++; if(appear[S[win_end]] <= expect[S[win_end]]) appearCharCnt ++; //cout << "appearCharCnt\t" <<appearCharCnt<< endl; if(appearCharCnt == T.size()) { // shrink the win start while (appear[S[win_start]] > expect[S[win_start]] ) { appear[S[win_start]]--; win_start++; } if ((win_end - win_start + 1) < minWidth) { minWidth = win_end - win_start + 1; min_start = win_start; //cout << "min_start\t" <<min_start << endl; //cout << "min_width\t" <<minWidth<< endl; } } } if (minWidth == INT_MAX) return ""; else return S.substr(min_start, minWidth); } };