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;
    }
};
相关推荐
青 春 记 忆1 天前
LeetCode 121. 买卖股票的最佳时机|Python 解法详解
python·算法·leetcode
Navigator_Z1 天前
LeetCode //C - 1203. Sort Items by Groups Respecting Dependencies
c语言·算法·leetcode
Scabbards_2 天前
面试Leetcode - Heap 堆
java·leetcode·面试
ValhallaCoder2 天前
Leetcode-hot100(2026.08.17)
python·算法·leetcode
青 春 记 忆2 天前
LeetCode 104. 二叉树的最大深度|Python 解法详解
python·算法·leetcode
evans在进步2 天前
LeetCode 198:打家劫舍——Java 动态规划详解
java·leetcode·动态规划
Nil2082 天前
leetcode 234回文链表
算法·leetcode·链表
ZC跨境爬虫2 天前
LeetCode 119. 杨辉三角 II(原地更新优化详解 + Java Python 实现)
java·python·leetcode
吃着火锅x唱着歌2 天前
LeetCode 3597.分割字符串
算法·leetcode·职场和发展
Nil2083 天前
leetcode 160相交链表
算法·leetcode·链表