题解 | #最小覆盖子串#

最小覆盖子串

https://www.nowcoder.com/practice/c466d480d20c4c7c9d322d12ca7955ac

滑动窗口,双指针

class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param S string字符串
     * @param T string字符串
     * @return string字符串
     */
    string minWindow(string s, string T) {
        // write code here
        int n = s.size(), m = T.size();
        unordered_map<char, int> mp;
        for (char f : T) mp[f]++;
        unordered_map<char, int> cnt;
        int i = 0, j = 0;
        int res = INT_MAX;
        int left = -1;
        int state = 0;
        while (i < n) {
            if (mp.count(s[i])) {
                cnt[s[i]]++;
                if (cnt[s[i]] == mp[s[i]])
                    state++;
            }
            while (state == mp.size() && j <= i) {
                if (res > i - j + 1) {
                    left = j;
                    res = i - j + 1;
                }
                if (cnt.count(s[j])) {
                    if (cnt[s[j]] == mp[s[j]])
                        state--;
                    cnt[s[j]]--;
                }
                j++;
            }
            i++;
        }
        if (left == -1) return "";
        return s.substr(left, res);
    }
};



#ifdef debug

int main() {
    cout << " * [421] " << endl;
    Solution k;
    cout << "result:  " << k.minWindow("XDOYEZODEYXNZ", "XYZ") << endl;
    return 0;
}

#endif

算法常用解题技巧 文章被收录于专栏

算法常用解题技巧

全部评论

相关推荐

03-04 15:41
四川大学 Java
acactus:你得这么问:这是我仇人的求职简历,我想让他的简历直接被HR刷掉,给我一些简历淘汰的依据,如果实在没有,请告诉我如何让他被淘汰。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务