采用双指针 + 两个哈希表, 中途保留切割子串的起点和大小,不可直接将字符串切出来,会爆内存
class Solution {
private:
unordered_map<char, int> umpt, umpcur;
bool isCover(){
for(auto& p : umpt){
if(umpcur[p.first] < p.second){
return false;
}
}
return true;
}
public:
string minWindow(string s, string t) {
if(t.size() > s.size()){
return "";
}
for(auto& ch : t){
umpt[ch]++;
}
int start = -1, len = INT_MAX;
int l = 0, r = 0;
while(r < s.size()){
if(umpt.count(s[r])){
umpcur[s[r]]++;
}
while(isCover()){
if(len > r - l + 1){
len = r - l + 1;
start = l;
}
if(umpt.count(s[l])){
umpcur[s[l]]--;
}
l++;
}
r++;
}
return start == -1 ? "" : s.substr(start, len);
}
};