力扣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);
    }
};
相关推荐
生信大杂烩4 分钟前
Xenium H&E空间原位可视化——细胞轮廓、基因表达与转录本可视化
python·算法·数据分析
linx29516 分钟前
第七章 · 标准库容器、算法与 ranges
c语言·开发语言·数据结构·c++·算法
钓鱼的肝20 分钟前
csp-j-s总结(4)
c++·经验分享·笔记·算法
橘子汽水16834 分钟前
Leetcode 763,45 划分字母区间 跳跃游戏II
数据结构·算法·leetcode
天天喝旺仔1 小时前
Git 内部原理深度解析:从 blob/tree/commit 对象到 packfile 与垃圾回收
数据结构·数据库·git·算法·哈希
AIGCmagic社区1 小时前
KITTI AbsRel从6.5压到5.4,Marigold V2用一张32GB卡把编辑DiT收成单步深度估计
人工智能·算法·aigc·ai多模态
青少儿编程课堂1 小时前
多源最短路与最小环(Floyd 算法图论解析)
c++·python·算法·bfs·信息学竞赛
6Hzlia1 小时前
【Classic 150 刷题计划】 LeetCode 228. 汇总区间 | C++ 锚点游标与断点检测法
c++·算法·leetcode
Edward The Bunny2 小时前
Leetcode Hot 100
数据结构·算法
hans汉斯2 小时前
数据挖掘|基于BP神经网络的少数民族村寨文化型旅游体验产品潜在游客挖掘
深度学习·神经网络·算法·yolo·软件工程·bp·汉斯出版社