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.
Subscribe to see which companies asked this question
class Solution {
public:
string minWindow(string s, string t) {
map<char, int> T_map;
for (int i=0; i<t.size(); i++)
{
if (T_map.find(t[i]) == T_map.end())
{
T_map[t[i]] = 1;
}
else
{
T_map[t[i]]++;
}
}
map<char, int> S_map;
int left = 0;
int right = 0;
int matchNum = 0;
int minLeft = 0;
int minRight = s.size();
bool found = false;
// 如何比较两个map的数是否match?
for (int i=0; i<s.size(); i++)
{
if (T_map.find(s[i]) != T_map.end())
{
if (S_map.find(s[i]) == S_map.end())
{
S_map[s[i]] = 0;
}
if (S_map[s[i]] < T_map[s[i]])
{
matchNum++;
}
S_map[s[i]]++;
}
if (matchNum == t.size())
{
found = true; //这里也要注意,有可能匹配不上
right = i;
while (true) //这个while循环比较关键,是用来找到最小range的
{
if (right-left < minRight-minLeft)
{
minLeft = left;
minRight = right;
}
int preLeft = left;
left++;
if (left > right) //这里是要注意的,left 不能大于right
break;
// 每次通过比较preLeft是否有多余来进行左缩
if (S_map.find(s[preLeft]) != S_map.end()) //这里也要注意,如果这个数不在 t里,直接跳过 (abc, bc)
{
S_map[s[preLeft]]--;
if (S_map[s[preLeft]] < T_map[s[preLeft]])
{
matchNum--;
break;
}
}
}
}
}
if (found)//这里注意
return s.substr(minLeft, minRight-minLeft+1);
else
return "";
}
};