problem:
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 empty string ""
.
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
这道题的要求是在给定的字符串S中找到最小的窗口使其完全包含字符串T中所有字符,如果不存在,则返回空串""
首先需要返回一个包含字符串中所有字符的窗口,其次这个窗口要最小。
1.返回一个window至少包含target中的所有字符
考虑到target中的string可能重复,所以使用一个hash来存储target中的string的分布情况。
2.在返回的window中,要尽可能地使得它最小。
所以就要尽可能地去掉不需要的部分,于是,对于每一个index结尾的窗口,看看它前面能丢掉多少个字符。丢掉的方式有两种,如果这个字符根本就不在needToFound中,那么可以丢掉,或者,如果这个字符在当前窗口中的数量超过了needToFound需要的数量,也可丢掉。
class Solution {
public:
string minWindow(string s, string t) {
int hasFound[256] = {0};
int needToFind[256] = {0};
int windowBegin = 0;
int windowEnd = 0;
int minwindowBegin = 0;
int minWindowEnd = 0;
//NOTE1: int minLength = S.length(); //minWindow("a", "a"): expected return "a", actual wrong answer "";
int minLength = INT_MAX;
string minStr = "";
for (int i =0; i < t.length(); ++i){
needToFind[t[i]]++;
}
int begin = 0, end = 0, count = 0;
//string str1 = "ADOBECODEBANC";
//string str2 = "ABC";
for (begin = 0, end = 0; end < s.length();++end) {
if (needToFind[s[end]]<0) continue;
hasFound[s[end]]++;
if (hasFound[s[end]] <= needToFind[s[end]])
count++;
if (count >= t.length()) {
while (needToFind[s[begin]] == 0 || hasFound[s[begin]] > needToFind[s[begin]]) { //NOTE2: two level logica
if (hasFound[s[begin]] > needToFind[s[begin]]) {
hasFound[s[begin]]--;
}
begin++;
}
windowBegin = begin;
windowEnd = end;
if (windowEnd - windowBegin + 1 < minLength) {
minLength = windowEnd - windowBegin + 1;
windowEnd = end;
windowBegin = begin;
minStr = s.substr(windowBegin, windowEnd - windowBegin + 1);
}
}
}
return minStr;
}
};