posts - 501,comments - 0,views - 23802

20230302 顺利通过
20230306 如果r扫描用while,不能贪心的减少不必要的字母
20230314 顺利通过
原题解

题目

约束

题解


class Solution {
public:
    unordered_map <char, int> ori, cnt;

    bool check() {
        for (const auto &p: ori) {
            if (cnt[p.first] < p.second) {
                return false;
            }
        }
        return true;
    }

    string minWindow(string s, string t) {
        for (const auto &c: t) {
            ++ori[c];
        }

        int l = 0, r = -1;
        int len = INT_MAX, ansL = -1, ansR = -1;

        while (r < int(s.size())) {
            if (ori.find(s[++r]) != ori.end()) {
                ++cnt[s[r]];
            }
            while (check() && l <= r) {
                if (r - l + 1 < len) {
                    len = r - l + 1;
                    ansL = l;
                }
                if (ori.find(s[l]) != ori.end()) {
                    --cnt[s[l]];
                }
                ++l;
            }
        }

        return ansL == -1 ? string() : s.substr(ansL, len);
    }
};

一些我自己看得更习惯的格式

class Solution {
public:
    unordered_map<char, int> ori, cnt;
    bool check(){
        for(auto it = ori.begin(); it != ori.end(); it ++){
            if(cnt[it->first] < it->second){
                return false;
            }
        }
        return true;
    }
    string minWindow(string s, string t) {
        for(int i = 0; i < t.size(); i ++){
            ori[t[i]] ++;
        }
        int l = 0, r = -1;
        int maxLen = 0x3f3f3f3f, ansl = -1, ansr = -1;
        int n = s.size();
        while(r < n){
            if(ori.find(s[++ r]) != ori.end()){//r
                ++ cnt[s[r]];
            }
            while(check() && l <= r){//l
                if(r - l + 1 < maxLen){
                    maxLen = r - l + 1;
                    ansl = l; 
                }
                if(ori.find(s[l]) != ori.end()){
                    -- cnt[s[l]];
                }
                l ++;
            }
        }
        return ansl == -1 ? "" : s.substr(ansl, maxLen);
    }
};
posted on   垂序葎草  阅读(13)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示