【leetcode】Minimum Window Substring

来源:互联网 发布:小孩学编程 编辑:程序博客网 时间:2024/05/21 06:37

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.

思路:

用两个索引表示滑动窗口的左右边界,在符合条件的窗口中更新最小窗口值。

代码

class Solution {public:    string minWindow(string s, string t) {        int require[256]={0};//t中字符出现的个数        bool exist[256]={false};//t中是否有的字符        for(auto c:t)        {            require[c]++;            exist[c]=true;        }        int start=0,end=-1;        int count=t.length();//t的长度        int result=INT_MAX;        int minStart=0;        while(end<(int)s.length()&&start<s.length())        {            if(count)//未完全匹配t,右窗口滑动            {                end++;                if(exist[s[end]]&&require[s[end]]>0)count--;                require[s[end]]--;//当前所需字符减一                            }else            {                if(result>end-start+1)                {                    result=end-start+1;//更新最小窗口值                    minStart=start;                }                require[s[start]]++;//起点所需字符加一,滑动左边窗口位置                if(exist[s[start]]&&require[s[start]]>0)//如果左边界字符在t中出现且移动窗口后没有多余此字符,则count加1;                    count++;                start++;            }        }        if(result!=INT_MAX)return s.substr(minStart,result);        else return "";    }};


0 0
原创粉丝点击