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);
    }
};
相关推荐
星空露珠4 分钟前
迷你世界脚本文字板接口:Graphics
数据结构·游戏·lua
eason_fan4 分钟前
前端手撕代码(bigo)
算法·面试
302wanger18 分钟前
ARTS-算法-长度最小的子数组
算法
lizz3143 分钟前
机器学习中的线性代数:奇异值分解 SVD
线性代数·算法·机器学习
_星辰大海乀1 小时前
LinkedList 双向链表
java·数据结构·链表·list·idea
MSTcheng.1 小时前
【C语言】动态内存管理
c语言·开发语言·算法
不去幼儿园1 小时前
【启发式算法】Dijkstra算法详细介绍(Python)
人工智能·python·算法·机器学习·启发式算法·图搜索算法
serve the people1 小时前
神经网络中梯度计算求和公式求导问题
神经网络·算法·机器学习
闻缺陷则喜何志丹1 小时前
【二分查找、滑动窗口】P10389 [蓝桥杯 2024 省 A] 成绩统计|普及+
c++·算法·蓝桥杯·二分查找·滑动窗口·洛谷·成绩
星空露珠2 小时前
迷你世界脚本显示板管理接口:DisPlayBoard
数据结构·游戏·lua