[LeetCode P76] Minimum Window Substring

4500 ワード

原題:
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.

問題解決の考え方:
//        ,          :   map template     ,      hash ,        
//        discuss,key point   ,     s.a~s.b    t      ,         a
//   s.c~s.b    t   ,        map  m[c]        0     a,        c, b  
//    0     ,        b a   ,   0   (a      ,        ),  a   O(n),b    O(n),       ,      O(2n)
class Solution {
public:
    string minWindow(string s, string t) {
        map<char, int> m;
        for (int i = 0; i < t.length(); ++i)
            if(m.count(t[i]))m[t[i]]++;
            else m[t[i]] = 1;
        int begin = 0, count = 0, start = 0, length = 1e7;
        for (int i = 0; i < s.length(); ++i)
        {
            // i   end
            char c = s[i];
            if (m.count(c) == 0)continue;
            m[c]--;
            if (count < m.size() && m[c] == 0) count++;
            // count             substring 
            if (count == m.size())
            {
                while(m.count(s[begin]) == 0 || (m[s[begin]]+1) <= 0)
                    if (m.count(s[begin])) m[s[begin++]]++;
                    else begin++;
                //    i,         begin,    begin         begin
                //          begin                 
                if (i - begin + 1 < length) length = i - (start = begin) + 1;
                //                ,      start  
            }
        }
        return length == 1e7 ? "" : s.substr(start, length);
    }
};