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;
    }
};
相关推荐
Nil2081 小时前
leetcode 48旋转图像
算法·leetcode·职场和发展
Nil2081 小时前
leetcode 206反转链表
算法·leetcode·链表
想吃火锅100514 小时前
【leetcode】200. 岛屿数量
算法·leetcode·职场和发展
Nil20815 小时前
leetcode 54螺旋矩阵
算法·leetcode·矩阵
evans在进步20 小时前
LeetCode 394:字符串解码——Java 单栈模拟与嵌套解析详解
java·python·leetcode
Nil20820 小时前
leetcode 189轮转数组
数据结构·算法·leetcode
吃着火锅x唱着歌21 小时前
LeetCode 3885.设计事件管理器
算法·leetcode·职场和发展
土司大王21 小时前
LeetCode hto100——字母异位词分组
java·算法·leetcode
土司大王1 天前
LeetCode hot100——两数之和
数据结构·算法·leetcode
.道阻且长.1 天前
7.LeetCode算法习题讲解--双指针--四数之和
算法·leetcode·职场和发展