复杂度不超过O(3m)
维护一个能找到答案的最小字符串区间,如果满足包含子串移动左指针,如果不满足移动右指针。
由于最后一次quick++会超出范围所以慢指针用whil。
typedef pair<int, int> PII;
class Solution {
public:
string minWindow(string s, string t) {
unordered_map<char, int> myMap, times;
int cnt = 0;
for(auto i : t)
{
myMap[i] ++;
cnt ++;
}
string ans;
if(t.length() > s.length()) return ans;
int currentcnt = 0;
PII posi = {0, 1e5};
for(int quick = 0, slow = 0; quick < s.length();)
{
if(currentcnt < cnt)
{
if(myMap.find(s[quick]) != myMap.end())
{
if(times[s[quick]] < myMap[s[quick]])
{
currentcnt++;
}
times[s[quick]] ++;
}
quick++;
}
while(currentcnt >= cnt)
{
if(quick - 1 - slow < posi.second - posi.first)
posi = {slow, quick - 1};
if(myMap.find(s[slow]) != myMap.end())
{
if(times[s[slow]] <= myMap[s[slow]])
{
currentcnt--;
}
times[s[slow]] --;
}
slow ++;
}
}
PII temp = {0, 1e5};
if(posi != temp) ans = s.substr(posi.first, posi.second - posi.first + 1);
return ans;
}
};