LeetCode HOT100 - 最小覆盖子串

滑动窗口

从 l = 0 开始不断移动右指针 r 找到一个能满足的窗口

然后缩小窗口直到不满足

接着就继续移动 r 到满足

重复这一个过程

合法性在于固定 l 时移动 r ,我们是在找让这个 l 满足的最小 r

固定 r 移动 l 是找让这个 r 满足的最大 l

并且这个过程中扫到的 l 一定不会更优,因为都是满足匹配的窗口,窗口自然是越小越好

class Solution {
public:
    string minWindow(string s, string t) {
        unordered_map<int, int> cnt;
        for (auto i : t) {
            cnt[i - 'a']++;
        } 
        int tot = t.size();
        cout << tot << '\n';
        int n = s.size();
        int l = 0, r = 0;
        int ansl = l, len = INT_MAX;
        while (r < n) {
            while (tot == 0) {
                if (++cnt[s[l++] - 'a'] > 0) {
                    if (len > (r - l + 1)) {
                        ansl = l - 1;
                        len = r - l + 1;
                    }
                    tot++;
                }
            }
            cout << l << ' ' << r << '\n';
            while (tot && r < n) {
                if (--cnt[s[r++] - 'a'] >= 0) {
                    tot--;
                }
                cout << r << ' ' << tot << '\n';
            }
            cout << l << ' ' << r << '\n';
            if (tot == 0) {
                if (r - l < len) {
                    ansl = l;
                    len = r - l;
                }
            }
        }
        while (tot == 0) {
            if (++cnt[s[l++] - 'a'] == 1) {
                if (len > (r - l + 1)) {
                    ansl = l - 1;
                    len = r - l + 1;
                }
                tot++;
            }
        }
        if (len == INT_MAX) {
            return "";
        }
        string ans = s.substr(ansl, len);
        return ans;
    }
};

好像有优化的思路,之后看看

posted @ 2026-05-09 17:35  rdcamelot  阅读(11)  评论(0)    收藏  举报