leetCode76. 最小覆盖子串

leetCode76. 最小覆盖子串


题目思路


代码

cpp 复制代码
// 双指针 + 哈希表
// 这里cnt维护过程:先找到能够匹配T字符串的滑动窗口,然后这个cnt就固定了,因为i向前移动的同时,j也会维护着向前
// 就是当又出现能够满足T字符串的时候,j就会向前移动,且对应的字符的删除工作也做好了,这样就可以动态的维护cnt不变
class Solution {
public:
    string minWindow(string s, string t) {
        unordered_map<char,int> hs, ht;

        // 用哈希表ht维护t中所有字符出现的次数
        for(auto c : t) ht[c]++;

        // 双指针算法维护滑动窗口
        string res = ""; // 定义答案
        int cnt = 0; // 维护滑动窗口中有效字符数量
        for(int i = 0, j = 0; i < s.size() ; i++){
            hs[s[i]]++; // i向前移动

            if(hs[s[i]] <= ht[s[i]]) cnt++; // 看对应字符是否有效
            while(hs[s[j]] > ht[s[j]]) hs[s[j++]] --; // 看j向前移动的时机,并且对应的hs值也应该减少
            if(cnt == t.size()){
                if(res.empty() || i - j + 1 < res.size()){
                    res = s.substr(j, i - j + 1);
                }
            }
        }

        return res;
    }
};
相关推荐
Navigator_Z21 小时前
LeetCode //C - 1240. Tiling a Rectangle with the Fewest Squares
c语言·算法·leetcode
稻米哟21 小时前
力扣100——双指针
算法·leetcode
橘子汽水1681 天前
Leetcode 198,118打家劫舍,杨辉三角
算法·leetcode
alphaTao1 天前
LeetCode 每日一题 2026/9/7-2026/9/13
算法·leetcode
土司大王1 天前
LeetCode 79 单词搜索:Java 回溯模板、网格 DFS 与剪枝优化
java·算法·leetcode·深度优先
All for pursuit.1 天前
【数组-5】560.和为K的子数组
数据结构·c++·算法·leetcode
土司大王2 天前
LeetCode 17 电话号码的字母组合:Java 回溯模板、多叉决策树与复杂度分析
java·leetcode·决策树
find1star2 天前
LeetCode 25:K 个一组翻转链表
java·数据结构·算法·leetcode·链表·职场和发展·动态规划