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);
    }
};
相关推荐
林下清风~5 分钟前
力扣hot100——347.前K个高频元素(cpp手撕堆)
算法·leetcode·职场和发展
进击的小白菜1 小时前
Java回溯算法解决非递减子序列问题(LeetCode 491)的深度解析
java·算法·leetcode
-一杯为品-2 小时前
【深度学习】#11 优化算法
人工智能·深度学习·算法
-qOVOp-2 小时前
zst-2001 上午题-历年真题 计算机网络(16个内容)
网络·计算机网络·算法
Swift社区2 小时前
涂色不踩雷:如何优雅解决 LeetCode 栅栏涂色问题
算法·leetcode·职场和发展
冠位观测者2 小时前
【Leetcode 每日一题】2900. 最长相邻不相等子序列 I
数据结构·算法·leetcode
努力写代码的熊大2 小时前
链表的中间结点数据结构oj题(力扣876)
数据结构·leetcode·链表
真的没有脑袋2 小时前
概率相关问题
算法·面试
y102121043 小时前
Pyhton训练营打卡Day27
java·开发语言·数据结构
daiwoliyunshang3 小时前
哈希表实现(1):
数据结构·c++