LeetCode 76. Minimum Window Substring

来源:互联网 发布:unity3d素材免费资源 编辑:程序博客网 时间:2024/05/18 18:53

76. Minimum Window Substring

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.

/*题意:从母串S中找到这样的子串,这个子串包含目标T串中的所有字符,并且该子串的长度最短思路:1、先扫描一遍T,把对应的字符及其出现的次数存到哈希表中2、然后开始遍历S,遇到T中的字符,就把对应的哈希表中的值减一,直到包含了T中的所有的字符,   纪录一个子串并更新最小子串值3、将子窗口的左边界向右移,略掉不在T中的字符*/class Solution {public:    string minWindow(string S, string T) {        if(T.length() > S.length()){            return "";        }        string res = "";        map<char, int>m;        for(int i = 0; i < T.length(); i++){            if(m.find(T[i]) != m.end())                 m[T[i]]++;            else                  m[T[i]] = 1;        }        int  l = 0, count = 0, minlen = INT_MAX;        for(int i = 0; i < S.length(); i++){            if(m.find(S[i]) != m.end()){                m[S[i]]--;                if(m[S[i]] >= 0)count++;                while(count == T.size()){                    if(i - l + 1 < minlen){                        minlen = i - l + 1;                        res = S.substr(l, minlen);                    }                    if(m.find(S[l]) != m.end()){                        m[S[l]]++;                        if(m[S[l]] > 0)count--;                    }                    l++;                }            }         }        return res;    }};


原创粉丝点击