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

Problem: 76. 最小覆盖子串

文章目录

题目描述

思路

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

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

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

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

复杂度

时间复杂度:

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);
    }
};
相关推荐
wuyk5551 分钟前
《WiFi 嵌入式物联网开发全套实战》 | 第 45 章【终章】WiFi 开发全套知识复盘 + 面试高频题 + 进阶路线
物联网·面试·职场和发展
葫三生42 分钟前
关于三生原理系列被技术开发社区批量收录或引发策展边界讨论的一种思考
大数据·人工智能·深度学习·算法·机器学习·数据挖掘·开源
catcatuncle42 分钟前
OpenWorkBuddy 部署排错手册:从源码启动到自己搭一个给团队用,七个最容易卡住的地方
算法
avi911144 分钟前
【AI教人】在Inspector显示所有Delegate-Odin Inspector之三
java·前端·算法·delegate·inspector·editor扩展·unity editor
淡海水1 小时前
06-02-源码-增量标记算法实现
算法·unity·c#·gc
碧海银沙音频科技研究院1 小时前
实现炬芯ATS308X的usb cdc 串口IAP 固件升级功能实现
人工智能·嵌入式硬件·深度学习·算法
云淡风轻~窗明几净1 小时前
角谷猜想与百度AI的对话dialog(原始稿)
人工智能·算法·机器学习·图论
小O的算法实验室2 小时前
ASOC,分层分数阶粒子群算法+无人机电场路径规划
算法
傅科摆 _ py2 小时前
链表力扣复习
数据结构·leetcode·链表
重生之小比特2 小时前
【算法拾光】二分查找|搜索插入位置 + x 的平方根
算法