原题链接:76. 最小覆盖子串
solution:
滑动窗口:是Leetcode 438 的升级版
438. 找到字符串中所有字母异位词_anieoo的博客-CSDN博客
class Solution {
public:
string minWindow(string s, string t) {
unordered_map<char,int> hash;
unordered_map<char,int> cnt; //统计窗口中字母数量
for(auto &c : t) hash[c]++; //存储t中所有字母和数量
string res = "";
int tot = hash.size(); //种类数目
int kinds = 0;
int n = s.size();
for(int i = 0,j = 0;i < n;i++) {
cnt[s[i]]++; //窗口中字母++
if(cnt[s[i]] == hash[s[i]]) kinds++; //如果窗口中某个字母数量等于t中对应字母数量,则种类数+1
while(cnt[s[j]] > hash[s[j]]) { //当窗口中最左端字母数量大于t中对应字母数量,滑动窗口
cnt[s[j]]--;
j++;
}
if(kinds == tot) { //种类数相等则保存
if(res == "" || res.length() > (i - j + 1))
res = s.substr(j,i - j + 1);
}
}
return res;
}
};