题解 | #最小覆盖子串#

最小覆盖子串

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

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

算法常用解题技巧

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-25 17:46
点赞 评论 收藏
分享
06-17 00:26
门头沟学院 Java
程序员小白条:建议换下项目,智能 AI 旅游推荐平台:https://github.com/luoye6/vue3_tourism_frontend 智能 AI 校园二手交易平台:https://github.com/luoye6/vue3_trade_frontend GPT 智能图书馆:https://github.com/luoye6/Vue_BookManageSystem 选项目要选自己能掌握的,然后最好能自己拓展的,分布式这种尽量别去写,不然你只能背八股文了,另外实习的话要多投,尤其是学历不利的情况下,多找几段实习,最好公司title大一点的
无实习如何秋招上岸
点赞 评论 收藏
分享
07-02 10:39
门头沟学院 Java
Steven267:说点真实的,都要秋招了,还没有实习,早干嘛去了,本来学历就差,现在知道急了,而且你这个简历完全可以写成一页,劣势太大了,建议转测试
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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