题目:
代码(首刷看解析 2024年3月3日):
class Solution {
public:
string minWindow(string s, string t) {
unordered_map<char, int> need;
int need_cnt = t.size();
int len;
for (const char& c: t) {
need[c]++;
}
string res;
for (int left = 0, right = 0; right < s.size(); ++right) {
if (need[s[right]] > 0) need_cnt--;
need[s[right]]--;
// 窗口已经覆盖全部字母
if (need_cnt == 0) {
// 缩小范围
while (need[s[left]] < 0) {
need[s[left]]++;
left++;
}
len = right - left + 1;
if (res.empty() || res.size() > len) res = s.substr(left, len);
// left指针指向下一个,寻找新范围
need[s[left]]++;
left++;
need_cnt++;
}
}
return res;
}
};