LeetCode 76. 最小覆盖子串
使用滑动窗口,解题思路参考了:
https://www.cnblogs.com/grandyang/p/4340948.html
代码:
class Solution {
public:
string minWindow(string s, string t) {
string res = "";
unordered_map<char, int> letterCnt;//t中字符和其对应出现的次数的映射
int left = 0, cnt = 0, minLen = INT_MAX;
for (char c : t) ++letterCnt[c];//扫描t统计letterCnt映射
for (int i = 0; i < s.length(); ++i) {
if (--letterCnt[s[i]] >= 0) ++cnt;//右指针移动同时更新letterCnt
while (cnt == t.size()) {
if (minLen > i - left + 1) {
minLen = i - left + 1;
res = s.substr(left, minLen);//更新minLen和res
}
if (++letterCnt[s[left]] > 0) --cnt;//移动左指针,收缩子串
++left;
}
}
return res;
}
};