76. 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 empty string ""
.
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
本题有难度。两个指针,map。(1)i指针扫描,tmap[ s[i] ]=0 说明子串里刚好有足够个s[i],count++
(2)当count = T.size()时,l指针开始扫,扫到一个就tmap[s[i]]++,因为l是子串左指针,说明缺失一个s[i],开始缺失就是子串开始的位置,更新长度
class Solution {
public:
string minWindow(string s, string t)
{
map<char,int> tmap;
for (int i = 0; i < t.size(); i++)
tmap[t[i]]++;
int count = 0;
int l = 0;
int left;//存目标子串开始位置
int length = s.size() + 1;//目标子串长度
for (int i = 0; i < s.size(); i++)
{
if(tmap.find(s[i]) != tmap.end())//子串开头肯定是在tmap里面
{
tmap[s[i]]--;
if (tmap[s[i]] >= 0) //这一步 >= 很关键。因为t中可能有重复的字母。 不能是 ==
count++; // >= 0 说明没有找多,因为找多了就 < 0
while (count == t.size())
{
if (tmap.find(s[l]) != tmap.end())
{
tmap[s[l]]++;
if (tmap[s[l]] > 0) // > 0代表开始缺失,说明找到了子串的开头.如果找到了还是 <= 0 那就说明本来就是多找的,根本不缺。
{
count--;
if (i-l+1 < length)
{
length = i-l+1;
left = l;
}
}
}
l++; //子串左边界++
}
}
}
return (length == s.size() + 1) ? "" : s.substr(left, length);
}
};