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);
    }
};
相关推荐
一只齐刘海的猫2 小时前
【Leetcode】找到字符串中所有字母异位词
算法·leetcode·职场和发展
海清河晏1112 小时前
数据结构 | 八大排序
数据结构·算法·排序算法
liulilittle3 小时前
固定数组时间轮的槽过载优化:桶链表与批次执行
网络·数据结构·链表
IronMurphy3 小时前
【算法五十七】146. LRU 缓存
算法·缓存
Irissgwe4 小时前
数据结构-栈和队列
数据结构·c++·c·栈和队列
两片空白4 小时前
数据容器集合set/frozenset
数据结构
凌波粒4 小时前
LeetCode--108.将有序数组转换为二叉搜索树(二叉树)
算法·leetcode·职场和发展
liulilittle4 小时前
KCC:在 BBR 思路上的一次探索
网络·tcp/ip·算法·bbr·通信·拥塞控制·kcc
浦信仿真大讲堂4 小时前
达索系统SIMULIA Abaqus 2026接触和约束的增强新功能介绍
人工智能·python·算法·仿真软件·达索软件
点云侠4 小时前
PCL 生成三棱锥点云
c++·算法·最小二乘法