题解 | #最小覆盖子串#

最小覆盖子串

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

class Solution {
public:
    /**
     * 
     * @param S string字符串 
     * @param T string字符串 
     * @return string字符串
     */
    
    string minWindow(string S, string T) {
        int left = 0, right = 0;
        //表示窗口左右位置的指针
        int start = 0, minLen = INT_MAX;
        //start 表示最后结果字符串开始位置,minlen表示最后字符串长度,二者可以表示一个字符串
        unordered_map<char, int> need;
        //need的存放字符串T的所有字符统计
        unordered_map<char, int> window;
        //window 存放现有的窗口中出现在need中的字符统计

        for (auto i:T)
            need[i]++;
        int match = 0;
        //window与need的匹配度

        while (right < S.length()) {
            char c1 = S[right];
            if (need.count(c1)) { // 看need字典中是否存在c1
                window[c1]++;
                if (window[c1] == need[c1]) // 如果窗口中出现的c1次数等于T字符串中的次数
                    match++;
            }
            right++;
            while (match == need.size()) { // 此处是need.size()不是T.size(),考虑到T中可能存在重复字符的因素
                //当匹配度等于need.size(),说明这段区间可以作为候选结果,更新ret
                if (right - left < minLen) {
                    minLen = right - left;
                    start = left;
                }
                char c2 = S[left];
                if (need.count(c2)) {
                    window[c2]--;
                    if (window[c2] < need[c2]) 
                        match--;
                }
                left++;
            }
        }
        return minLen == INT_MAX ? "" : S.substr(start, minLen);
    }

};
全部评论

相关推荐

07-02 10:44
门头沟学院 C++
码农索隆:太实诚了,告诉hr,你能实习至少6个月
点赞 评论 收藏
分享
05-14 20:34
门头沟学院 Java
窝补药贝八股:管他们,乱说,反正又不去,直接说680
点赞 评论 收藏
分享
找个工作&nbsp;学历是要卡的&nbsp;要求是高的&nbsp;技能不足是真的&nbsp;实习经验是0的&nbsp;简历无处可写是事实的&nbsp;钱不好赚是真的&nbsp;想躺平又不敢躺&nbsp;也不甘心躺&nbsp;怕自己的灵感和才华被掩埋甚至从未被自己发现&nbsp;又质疑自己是否真正有才华
码农索隆:你现在啊,你心里都明白咋回事,但是你没办法改变现状,一想到未来,你又没有信心狠下心来在当下努力。 得走出这种状态,不能一直困在那里面,哪不行就去提升哪,你一动不动那指定改变不了未来,动起来,积少成多才能越来越好
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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