每日一练——Minimum Window Substring

来源:互联网 发布:乐清市知临中学 编辑:程序博客网 时间:2024/06/14 14:44

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.

Subscribe to see which companies asked this question

<span style="font-family:Microsoft YaHei;font-size:12px;">class Solution {public:    string minWindow(string s, string t) {        int start, end;        start = end = 0;        int count = 0;        int mps[128] = {0}, mpt[128] = {0};        for (int i = 0; i < t.size(); i++)        {            mpt[t[i]] ++;        }        int m = t.size();        string min_str;        while (start < s.size() && end < s.size())        {            while (end < s.size() && count < m)            {                mps[s[end]]++;                if (mps[s[end]] <= mpt[s[end]] )//mps[s[end]]增加1后未达到或刚好达到匹配数量,那么count++                {                    count++;                }                end++;            }            if (count < m)            {                return min_str;            }            while (start < s.size() && count == m)            {                mps[s[start]]--;                if (mps[s[start]] < mpt[s[start]] )//mps[s[start]]减少1刚好少于匹配数量,那么count--                {                    count--;                }                start++;            }            string tmp = s.substr(start - 1, end - start + 1);            if (min_str.empty() || min_str.size() > tmp.size())            {                min_str = tmp;            }        }        return min_str;    }};</span>


0 0