AcWing
  • 首页
  • 课程
  • 题库
  • 更多
    • 竞赛
    • 题解
    • 分享
    • 问答
    • 应用
    • 校园
  • 关闭
    历史记录
    清除记录
    猜你想搜
    AcWing热点
  • App
  • 登录/注册

LeetCode 76. 最小覆盖子串    原题链接    中等

作者: 作者的头像   Yuze_Neko ,  2025-03-20 21:19:45 · 福建 ,  所有人可见 ,  阅读 7


0


复杂度不超过O(3m)

维护一个能找到答案的最小字符串区间,如果满足包含子串移动左指针,如果不满足移动右指针。
由于最后一次quick++会超出范围所以慢指针用whil。

typedef pair<int, int> PII;

class Solution {
public:
    string minWindow(string s, string t) {
        unordered_map<char, int> myMap, times;
        int cnt = 0;
        for(auto i : t)
        {
            myMap[i] ++;
            cnt ++;
        }
        string ans;

        if(t.length() > s.length()) return ans;
        int currentcnt = 0;
        PII posi = {0, 1e5};
        for(int quick = 0, slow = 0; quick < s.length();)
        {
            if(currentcnt < cnt)
            {
                if(myMap.find(s[quick]) != myMap.end())
                {
                    if(times[s[quick]] < myMap[s[quick]])
                    {
                        currentcnt++;
                    } 
                    times[s[quick]] ++;
                }
                quick++;
            }
            while(currentcnt >= cnt)
            {
                if(quick - 1 - slow < posi.second - posi.first)
                    posi = {slow, quick - 1};
                if(myMap.find(s[slow]) != myMap.end())
                {
                    if(times[s[slow]] <= myMap[s[slow]])
                    {
                        currentcnt--;
                    }
                    times[s[slow]] --;
                }
                slow ++;
            }
        }
        PII temp = {0, 1e5};
        if(posi != temp) ans = s.substr(posi.first, posi.second - posi.first + 1);
        return ans;
    }
};

0 评论

App 内打开
你确定删除吗?
1024
x

© 2018-2025 AcWing 版权所有  |  京ICP备2021015969号-2
用户协议  |  隐私政策  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标 qq图标
请输入绑定的邮箱地址
请输入注册信息