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;
    }
};
相关推荐
菜鸡儿齐8 分钟前
leetcode-搜索插入位置
数据结构·算法·leetcode
52Hz1189 分钟前
力扣394.字符串解码、739.每日温度、84.柱状图中最大的矩形
python·算法·leetcode
Swift社区21 分钟前
LeetCode 390 消除游戏 - Swift 题解
leetcode·游戏·swift
踩坑记录36 分钟前
leetcode hot100 131. 分割回文串 medium 递归回溯
leetcode
踢足球092940 分钟前
寒假打卡:2026-2-24
数据结构·算法·leetcode
样例过了就是过了1 小时前
LeetCode热题100 环形链表
算法·leetcode·链表
努力学算法的蒟蒻1 小时前
day95(2.24)——leetcode面试经典150
算法·leetcode·面试
菜鸡儿齐2 小时前
leetcode-搜索二维矩阵
算法·leetcode·矩阵
Charlie_lll2 小时前
力扣解题-无重复字符的最长子串
后端·算法·leetcode
iAkuya12 小时前
(leetcode)力扣100 76数据流的中位数(堆)
算法·leetcode·职场和发展