leetcode76 Minimum Window Substring

给定两个字符串s和t, 找到s的一个子串,使得t的每个字符都出现在子串中,求最短的子串

由于要每个字符出现,所以顺序其实没有关系

因此我们可以定义一个map,统计t中字符出现次数

然后在s中慢慢挪动滑动窗口,如果符合要求就缩短滑动窗口,直到不符合,然后继续移动

cpp 复制代码
class Solution {
public:
    string minWindow(string s, string t) {
        int ans = -1, ans_len = -1, n = s.size(), m = t.size();
        if(n < m)return "";
        unordered_map<char, int> mp;
        for(char& c:t)++mp[c];
        int cnt = mp.size(), pre = 0;
        for(int i = 0; i < n; ++i){
            auto it = mp.find(s[i]);
            if(it == mp.end())continue;
            --it->second;
            if(it->second == 0){
                --cnt;
                if(cnt == 0){
                    if(m == 1)return t;
                    if(ans_len == -1 || i - pre + 1 < ans_len){
                        ans_len = i - pre + 1;
                        ans = pre;
                    }
                    while(pre < i){
                        auto it2 = mp.find(s[pre]);
                        ++pre;
                        if(it2 == mp.end()){
                            if(i - pre + 1 < ans_len){
                                ans_len = i - pre + 1;
                                ans = pre;
                            }
                            continue;
                        }
                        ++it2->second;
                        if(it2->second == 1){
                            ++cnt;
                            break;
                        }
                        else{
                            if(i - pre + 1 < ans_len){
                                ans_len = i - pre + 1;
                                ans = pre;
                            }
                        }
                    }
                    
                    while(pre < i){
                        auto it2 = mp.find(s[pre]);
                        if(it2 == mp.end()){
                            ++pre;
                            continue;
                        }
                        else{
                            break;
                        }
                    }
                }
            }
        }
        
        if(ans == -1)return "";
        return s.substr(ans, ans_len);
    }
};
相关推荐
沐怡旸40 分钟前
【算法--链表】114.二叉树展开为链表--通俗讲解
算法·面试
tju新生代魔迷1 小时前
数据结构:双向链表
数据结构·链表
一只懒洋洋1 小时前
K-meas 聚类、KNN算法、决策树、随机森林
算法·决策树·聚类
方案开发PCBA抄板芯片解密2 小时前
什么是算法:高效解决问题的逻辑框架
算法
songx_992 小时前
leetcode9(跳跃游戏)
数据结构·算法·游戏
学c语言的枫子3 小时前
数据结构——双向链表
c语言·数据结构·链表
小白狮ww3 小时前
RStudio 教程:以抑郁量表测评数据分析为例
人工智能·算法·机器学习
AAA修煤气灶刘哥3 小时前
接口又被冲崩了?Sentinel 这 4 种限流算法,帮你守住后端『流量安全阀』
后端·算法·spring cloud
Boop_wu4 小时前
[数据结构] 栈 · Stack
数据结构
kk”4 小时前
C语言快速排序
数据结构·算法·排序算法