前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 76 Minimum Window Substring

Leetcode 76 Minimum Window Substring

作者头像
triplebee
发布2018-01-12 15:01:01
5660
发布2018-01-12 15:01:01
举报
文章被收录于专栏:计算机视觉与深度学习基础

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.

找出包含给定串所有字符的最小子串

两个指针向后滑,用map记录出现字符的次数。

代码语言:javascript
复制
class Solution {
public:
    string minWindow(string s, string t) 
    {
        int maxlen=INT_MAX;
        string result;
        unordered_map<char,int> mp,mp2;
        int cnt=t.size();
        for(int i=0;i<cnt;i++) mp[t[i]]++;
        for(int st=0,en=0;en<s.size();en++)
        {
            if(mp[s[en]]>0 )
            {
                mp2[s[en]]++;
                if(mp2[s[en]]<=mp[s[en]]) cnt--;
            }
            if(cnt==0)
            {
                while((mp2[s[st]]==0 || mp2[s[st]]>mp[s[st]]) && st<=en) 
                {
                    if(mp2[s[st]]>mp[s[st]]) mp2[s[st]]--;
                    st++;
                }
                if(en-st+1<maxlen) 
                {
                    maxlen=en-st+1;
                    result=s.substr(st,en-st+1);
                }
                cnt++;
                mp2[s[st]]--;
                st++;
            }
        }
        return result;
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016-09-23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档