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 2023-02-26 20:00  垂序葎草  阅读(10)  评论(0编辑  收藏  举报