76. Minimum Window Substring (Hard)

Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).

For example, S = "ADOBECODEBANC" T = "ABC" Minimum window is "BANC".

Note: If there is no such window in S that covers all characters in T, return the empty string "".

If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.

Solution: Hash Table, Two Pointers

Time Complexity: $$O(n)$$

这道题的要求是要在O(n)的时间度里实现找到这个最小窗口字串,那么暴力搜索Brute Force肯定是不能用的,我们可以考虑哈希表,其中key是T中的字符,value是该字符出现的次数。

  • 我们最开始先扫描一遍T,把对应的字符及其出现的次数存到哈希表中。

  • 然后开始遍历S,遇到T中的字符,就把对应的哈希表中的value减一,直到包含了T中的所有的字符,纪录一个字串并更新最小字串值。

  • 将子窗口的左边界向右移,略掉不在T中的字符,如果某个在T中的字符出现的次数大于哈希表中的value,则也可以跳过该字符。

version 1: 26ms

class Solution {
public:
    string minWindow(string s, string t) {
        unordered_map<char, int> m;
        for (auto c: t) ++m[c];
        int left = 0, minlen = s.size()+1, count = 0;
        string res;
        for (int i = 0; i < s.size(); ++i) {
            if (m.count(s[i])) {
                --m[s[i]];
                if (m[s[i]] >= 0) ++count;
                while (count == t.size()) {
                    if (i-left+1 < minlen) {
                        minlen = i-left+1;
                        res = s.substr(left, minlen);
                    }
                    if (m.count(s[left])) {
                        ++m[s[left]];
                        if (m[s[left]] > 0) --count;
                    }
                    ++left;
                }
            }
        }
        return res;
    }
};

version 2: 12ms

class Solution {
public:
    string minWindow(string s, string t) {
        vector<int> map(128,0);
        for (auto c: t) ++map[c];

        int left = 0, right = 0, head = 0;
        int count = t.size(), minlen = s.size()+1;

        while (right < s.size()) {
            if (map[s[right++]]-- > 0) --count;
            while (count == 0) {
                if (right-left < minlen) minlen = right-(head=left);
                if (map[s[left++]]++ == 0) ++count;
            }
        }
        return minlen == s.size()+1 ? "":s.substr(head, minlen);
    }
};

results matching ""

    No results matching ""