码迷,mamicode.com
首页 > Windows程序 > 详细

leetcode73:minmum-window-substring

时间:2020-08-03 14:50:55      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:get   comm   boa   div   put   来源   nbsp   ssi   ext   

题目描述

给出两个字符串S和T,要求在O(n)的时间复杂度内在S中找出最短的包含T中所有字符的子串。
例如:
S ="ADOBECODEBANC"
T ="ABC"
找出的最短子串为"BANC".
注意:
如果S中没有包含T中所有字符的子串,返回空字符串 “”;
满足条件的子串可能有很多,但是题目保证满足条件的最短的子串唯一。

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.

示例1

输入

复制
"ADOBECODEBANC","ABC"

输出

复制
"BANC"

链接:https://www.nowcoder.com/questionTerminal/c466d480d20c4c7c9d322d12ca7955ac?f=discussion
来源:牛客网

class Solution {
public:
    //维持一个窗口滑动,左边是left,右边是right,然后判断是否包含T
    string minWindow(string S, string T)
    {
        string result;
        if(!S.size() || !T.size())
        {
            return result;
        }
        map<char, int>Tmap;   //存储T字符串里字符,便于与S匹配
        int left = 0;       //左边窗口,起始为0
        int count = 0;      //计数器,对窗口内T串字符数量进行计数,起始为0
        //装载T串
        int minlen = S.size() + 1;      //最小窗口,便于比较最后取最小的,初始化取最大
        for(int i = 0; i < T.size(); ++i)
        {
            Tmap[T[i]]++;
        }
        //移动右边窗口
        for(int right = 0; right < S.size(); ++right)
        {
            if(Tmap.find(S[right]) != Tmap.end())   //当窗口内部有T中的字符
            {
                if(Tmap[S[right]] > 0)
                {
                    count++;            //计数器+1
                }
                Tmap[S[right]]--;   //去掉包含的,剩下都是没包含的
                while(count == T.size())//当窗口内有T的所有字符,就要开始移动左窗口啦
                {
                    if(Tmap.find(S[left]) != Tmap.end())
                    {
                        //好了,这就是一个包含字符串的窗口范围:left ~ right,
                        //判断是否比当前窗口还小,是就取串
                        if(minlen > right - left + 1)
                        {
                            //更新窗口大小
                            minlen = right -left + 1;
                            result = S.substr(left, right - left + 1);
                        }
                        //舍弃窗口左边字符串,继续移动窗口
                        Tmap[S[left]]++;
                        if(Tmap[S[left]] > 0)            //如果左边连续相同,则count不递减,窗口需要继续向右移动
                        {
                            count--;
                        }
                    }
                    left++;             //移动左窗口
                }
            }
        }
        return result;
    }
};





leetcode73:minmum-window-substring

标签:get   comm   boa   div   put   来源   nbsp   ssi   ext   

原文地址:https://www.cnblogs.com/hrnn/p/13426148.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!