题目描述
给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 “” 。
样例
示例 1:
输入:s = "ADOBECODEBANC", t = "ABC"
输出:"BANC"
解释:最小覆盖子串 "BANC" 包含来自字符串 t 的 'A'、'B' 和 'C'。
示例 2:
输入:s = "a", t = "a"
输出:"a"
解释:整个字符串 s 是最小覆盖子串。
示例 3:
输入: s = "a", t = "aa"
输出: ""
解释: t 中两个字符 'a' 均应包含在 s 的子串中,
因此没有符合条件的子字符串,返回空字符串。
C++ 代码
class Solution {
public:
string minWindow(string s, string t) {
unordered_map<char, int> hash;
for (auto c : t) hash[c] ++;
int cnt = hash.size();
string res;
for (int i = 0, j = 0, u = 0; i < s.size(); i ++)
{
if (hash[s[i]] == 1) u ++; // 加上当前字母已包含足够当前的这种字母
hash[s[i]] --; // 每次多加进来字母,则从总数中减掉一个
while (hash[s[j]] < 0) hash[s[j ++]] ++; // 判断j能否向后移动
if (u == cnt)
{
if (res.empty() || res.size() > i - j + 1) res = s.substr(j, i - j + 1);
// 注意不能直接return 因为后面还有可能有最优解
}
}
return res;
}
};