76. 最小覆盖子串
给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 “” 。
// https://leetcode.cn/problems/minimum-window-substring/solution/tong-su-qie-xiang-xi-de-miao-shu-hua-dong-chuang-k/
class Solution {
public:
string minWindow(string s, string t) {
if(s.size() < t.size())
return "";
unordered_map<char, int> need;
int count = t.size();
for(auto& c : t)
need[c]++;
int left = 0;
int size = INT_MAX;
int start = 0;
for(int right = 0; right < s.size(); right++)
{
if(need[s[right]] > 0)
count--;
need[s[right]]--; //放到滑动窗口中,https://leetcode.cn/problems/minimum-window-substring/solution/tong-su-qie-xiang-xi-de-miao-shu-hua-dong-chuang-k/
if(count == 0)
{
while(left < right && need[s[left]] < 0)
{
need[s[left]]++; //滑出窗口
left++;
}
if(right-left+1 < size)
{
size = right-left+1;
start = left;
}
need[s[left]]++;
left++;
count++;
}
}
if(size == INT_MAX)
return "";
else
return s.substr(start,size);
}
};
值得注意的是,只要某个元素包含在滑动窗口中,我们就会在need中存储这个元素的数量,如果某个元素存储的是负数代表这个元素是多余的。比如当need等于{‘A’:-2,‘C’:1}时,表示当前滑动窗口中,我们有2个A是多余的,同时还需要1个C。这么做的目的就是为了步骤二中,排除不必要的元素,数量为负的就是不必要的元素,而数量为0表示刚刚好。
文章介绍了一种解决LeetCode上的最小覆盖子串问题的算法,使用滑动窗口来遍历字符串s,通过维护一个哈希映射need记录所需字符及其数量。当窗口内字符满足t的所有字符时,更新最小子串的长度和起始位置。若无满足条件的子串,返回空字符串。
855

被折叠的 条评论
为什么被折叠?



