题解 | 最小覆盖子串

最小覆盖子串

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

恶心,题目文字没说子串的数量也要算进去,虽然示例2里展示了重复字符数量的问题,但我没看示例2)

下面提供两个版本的

使用reducewindow1和satisfywindow1的是只要提取的子串的字符集合包含目标子串即可。

使用xxx2和yyy2的是提取的子串的每个字符的数量也要大于等于目标子串的对应字符数量。

#include <limits>
#include <unordered_map>
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param S string字符串
     * @param T string字符串
     * @return string字符串
     */
    static unordered_map<char, int> stat_target;
    static bool initialized;
    bool reducewindow1(unordered_map<char, int>& stats, string target) {
        for (auto ch : target)
            if (stats[ch] < 1) return false;
        return true;
    }
    bool reducewindow2(unordered_map<char, int>& stats, string target) {
        for (auto ch : target)
            if (stats[ch] < stat_target[ch]) return false;
        return true;
    }

    bool satisfywindow1(unordered_map<char, int>& stats, string target) {
        for (auto ch : target) if (stats[ch] < 1) return false;
        return true;
    }

    bool satsifywindow2(unordered_map<char, int>& stats, string target) {
        for (auto ch : target) if (stats[ch] < stat_target[ch]) return false;
        return true;
    }

    string minWindow(string S, string T) {
        if (S.size() < T.size()) return "";
        for (auto ch : T) stat_target[ch] = 0;
        for (auto ch : T) stat_target[ch] += 1;
        this->initialized = true;
        unordered_map<char, int> stats;
        for (auto ch : S) stats[ch] = 0;
        int l = 0, r = 0;
        int minstart = 0, minlen = numeric_limits<int>::max();
        while ( r < S.size()) {
            while (r < S.size() && !satsifywindow2(stats, T)) stats[S[r++]] += 1;
            while (reducewindow2(stats, T)) stats[S[l++]] -= 1;
            if (r - l + 1 < minlen) {
                minlen = r - l + 1;
                minstart = l - 1;
            }
        }
        if (minstart < 0) return "";
        return S.substr(minstart, minlen);
    }
};

unordered_map<char, int> Solution::stat_target{};
bool Solution::initialized = false;

全部评论

相关推荐

09-22 09:42
门头沟学院 Java
牛客37185681...:马德,我感觉这是我面过最恶心的公司,一面是两个女hr,说什么实习前几个月属于试用期,试用期过了才能转成正式实习生,我***笑了,问待遇就是不说,问能不能接受全栈,沙币公司
如果可以选,你最想去哪家...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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