思路:
两个指针控制,尾指针记录当前到了哪个位置,头指针记录当前识别的最小t的开始位置,通过控制头尾指针的移动标记最小window的位置。
时间复杂度O(N),空间复杂度O(1)。
class Solution {
public:
string minWindow(string s, string t) {
if(s.empty()) return "";
if(s.size() < t.size()) return "";
//hash table
const int ASCII_MAX = 256;
int appear_count[ASCII_MAX];
int expect_count[ASCII_MAX];
fill(appear_count, appear_count + ASCII_MAX, 0);
fill(expect_count, expect_count + ASCII_MAX, 0);
//initialize
int minWidth = INT_MAX, min_start = 0;//window's size, starting point
int wnd_start = 0;
int appeared = 0;
for(int i = 0; i < t.size(); ++i) {
expect_count[t[i]]++;
}
for(int end = 0; end < s.size(); ++end) {
if(expect_count[s[end]] > 0) {
appear_count[s[end]]++;
if(appear_count[s[end]] <= expect_count[s[end]]) {
appeared++;
}
}
if(appeared == t.size()) {//find a complete t in s
while(appear_count[s[wnd_start]] > expect_count[s[wnd_start]] || expect_count[s[wnd_start]] == 0) {
appear_count[s[wnd_start]]--;
wnd_start++;
}
if(minWidth > end - wnd_start + 1) {
minWidth = end - wnd_start + 1;
min_start = wnd_start;
}
}
}
if(minWidth == INT_MAX) return "";
else return s.substr(min_start, minWidth);
}
};