题解 | #最小覆盖子串#

最小覆盖子串

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

#include <string>
#include <unordered_map>
class Solution {
public:
    /**
     * 
     * @param S string字符串 
     * @param T string字符串 
     * @return string字符串
     */
    string minWindow(string S, string T) {
        // write code here
        int m = S.size();
        int n = T.size();
        string res = S + "max";
        unordered_map<char, int> smap,tmap;
        for(int i = 0;i<n;++i)
            tmap[T[i]]++;
        int left = 0;
        int count = 0;
        for(int right = 0;right < m;++right)
        {
            if(tmap[S[right]] > smap[S[right]])
                count++;
            smap[S[right]]++;
            while(left < right && smap[S[left]] > tmap[S[left]])
                smap[S[left++]]--;
            if(count == n)
            {
                if(right-left+1 < res.size())
                    res = S.substr(left,right-left+1);
            }
        }
        return res == S + "max"? "":res;
    }
};

全部评论

相关推荐

06-16 15:04
黑龙江大学 Java
零OFFER战士:另一个版本查看图片
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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