力扣76. 最小覆盖子串(滑动窗口)

Problem: 76. 最小覆盖子串

文章目录

题目描述

思路

1.定义两个map集合need和window(以字符作为键,对应字符出现的个数作为值),将子串t存入need中;

2.定义左右指针left、right均指向0(形成窗口),定义int类型变量len记录最小窗口长度,valid记录当前窗口否存最短子串中的字符个数

3.向右扩大窗口,遍历到到的字符c如果在need中时,window[c]++ ,同时如果window[c] == need[c],则valid++

4.如果valid == need.size() ,则表示可以开始收缩窗口,并更新最小窗口禅读 (如果移除的字符在need中,同时window[d] == need[d],则valid--,window[d]--);

复杂度

时间复杂度:

O ( n ) O(n) O(n);其中 n n n为字符串 s s s的长度

空间复杂度:

O ( n ) O(n) O(n)

Code

cpp 复制代码
class Solution {
public:
    /**
     * Two pointer
     *
     * @param s Given string
     * @param t Given string
     * @return string
     */
    string minWindow(string s, string t) {
        unordered_map<char, int> need;
        unordered_map<char, int> window;
        for (char c: t) {
            need[c]++;
        }
        int left = 0;
        int right = 0;
        int valid = 0;
        // Records the starting index and length of the minimum overlay substring
        int start = 0;
        int len = INT_MAX;
        while (right < s.size()) {
            //c is the character moved into the window
            char c = s[right];
            // Move the window right
            right++;
            // Perform some column updates to the data in the window
            if (need.count(c)) {
                window[c]++;
                if (window[c] == need[c]) {
                    valid++;
                }
            }
            // Determine whether to shrink the left window
            while (valid == need.size()) {
                // Update the minimum overlay substring
                if (right - left < len) {
                    start = left;
                    len = right - left;
                }
                //d is the character to be moved out of the window
                char d = s[left];
                // Move the window left
                left++;
                // Perform some column updates to the data in the window
                if (need.count(d)) {
                    if (window[d] == need[d]) {
                        valid--;
                    }
                    window[d]--;
                }
            }
        }
        // Returns the minimum overlay substring
        return len == INT_MAX ? "" : s.substr(start, len);
    }
};
相关推荐
凌肖战29 分钟前
力扣网编程55题:跳跃游戏之逆向思维
算法·leetcode
黑听人41 分钟前
【力扣 简单 C】70. 爬楼梯
c语言·leetcode
88号技师1 小时前
2025年6月一区-田忌赛马优化算法Tianji’s horse racing optimization-附Matlab免费代码
开发语言·算法·matlab·优化算法
ゞ 正在缓冲99%…2 小时前
leetcode918.环形子数组的最大和
数据结构·算法·leetcode·动态规划
Kaltistss3 小时前
98.验证二叉搜索树
算法·leetcode·职场和发展
知己如祭3 小时前
图论基础(DFS、BFS、拓扑排序)
算法
mit6.8243 小时前
[Cyclone] 哈希算法 | SIMD优化哈希计算 | 大数运算 (Int类)
算法·哈希算法
c++bug3 小时前
动态规划VS记忆化搜索(2)
算法·动态规划
哪 吒3 小时前
2025B卷 - 华为OD机试七日集训第5期 - 按算法分类,由易到难,循序渐进,玩转OD(Python/JS/C/C++)
python·算法·华为od·华为od机试·2025b卷
军训猫猫头4 小时前
1.如何对多个控件进行高效的绑定 C#例子 WPF例子
开发语言·算法·c#·.net