力扣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);
    }
};
相关推荐
u01110267511 分钟前
工具页案例图如何编写 alt让图片说明与处理场景对应
java·前端·javascript·图像处理·人工智能·算法·ai作画
阿狗童鞋15 分钟前
数据结构与算法实战指南
数据结构·算法
Navigator_Z37 分钟前
LeetCode //C - 1275. Find Winner on a Tic Tac Toe Game
c语言·算法·leetcode
未来之窗软件服务40 分钟前
递归时间复杂度演算T (n)=aT (n/b)+f (n)-东方仙盟
算法·仙盟创梦ide·东方仙盟
垆边人似月.1 小时前
华为机考题:明明的随机数
数据结构·算法·华为
我命由我123452 小时前
Photoshop - 将Photoshop图像置入其他应用程序
学习·ui·职场和发展·求职招聘·职场发展·学习方法·photoshop
Doubbbbbbble云2 小时前
多维空间索引结构R树与KD树性能对比研究4
算法
海上小飞龙2 小时前
【KMP算法-中篇】next 数组的递推:往前填一位,靠的是往回退几步
算法
keyipatience2 小时前
B树详解:从零构建平衡多路搜索树
数据结构·b树·算法·图搜索
FluxArt2 小时前
GPT Image 2.5 多图参考怎么用:Flux Art 生成与编辑教程
数据结构·gpt·算法