力扣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);
    }
};
相关推荐
纪元A梦2 小时前
贪心算法应用:化工反应器调度问题详解
算法·贪心算法
深圳市快瞳科技有限公司2 小时前
小场景大市场:猫狗识别算法在宠物智能设备中的应用
算法·计算机视觉·宠物
liulilittle2 小时前
OPENPPP2 —— IP标准校验和算法深度剖析:从原理到SSE2优化实现
网络·c++·网络协议·tcp/ip·算法·ip·通信
superlls5 小时前
(算法 哈希表)【LeetCode 349】两个数组的交集 思路笔记自留
java·数据结构·算法
田里的水稻5 小时前
C++_队列编码实例,从末端添加对象,同时把头部的对象剔除掉,中的队列长度为设置长度NUM_OBJ
java·c++·算法
纪元A梦5 小时前
贪心算法应用:保险理赔调度问题详解
算法·贪心算法
Jayden_Ruan6 小时前
C++逆向输出一个字符串(三)
开发语言·c++·算法
点云SLAM7 小时前
C++ 常见面试题汇总
java·开发语言·c++·算法·面试·内存管理
叙白冲冲7 小时前
哈希算法以及面试答法
算法·面试·哈希算法
YuTaoShao8 小时前
【LeetCode 每日一题】1277. 统计全为 1 的正方形子矩阵
算法·leetcode·矩阵