LeetCode: Minimum Window Substring

来源:互联网 发布:淘宝店铺联盟怎么开通 编辑:程序博客网 时间:2024/06/10 14:56

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 emtpy string "".

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

class Solution {public:    string minWindow(string S, string T) {        int head = 0, back = 0, min = INT_MAX;        string result = "";        map<char, int> counts;        map<char, int> cur;        int match = 0;        for(int i = 0; i < T.size(); i++)        {            counts[T[i]]++;        }        for(int i = 0; i < S.size(); i++)        {            if(counts[S[i]] > 0)            {                cur[S[i]]++;                if(cur[S[i]] <= counts[S[i]])                    match++;                if(match == T.size())                {                    while(counts[S[head]] <= 0 || cur[S[head]] > counts[S[head]])                    {                        cur[S[head]]--;                        head++;                    }                    if(min > i-head+1)                    {                        min = i-head+1;                        result = S.substr(head, i-head+1);                    }                            cur[S[head]]--;                    match--;                    head++;                                    }            }         }        return result;    }};

Round 2:

class Solution {public:    string minWindow(string S, string T) {        unordered_map<char, int> map;        int min = INT_MAX;        string result;        for(int i = 0; i < T.size(); i++)        {            map[T[i]]++;        }        int match = 0, start = 0;        for(int i = 0; i < S.size(); i++)        {            if(map.find(S[i]) != map.end())            {                map[S[i]]--;                if(map[S[i]] >= 0)                {                    match++;                }                if(match == T.size())                {                    while(map.find(S[start]) == map.end() || map[S[start]] < 0)                    {                        if(map.find(S[start]) != map.end())                            map[S[start]]++;                        start++;                    }                    if(i-start+1 < min)                     {                        min = i-start+1;                        result = S.substr(start, i-start+1);                    }                    map[S[start]]++;                    match--;                    start++;                }            }        }        return result;    }};


0 0