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

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

采用双指针,end指针逐渐增加,当begin与end之间包含所有t后,后移begin,找到最小substr,并记录,最后输出最小substr。边界条件,begin处的字母属于t且在该区域中仅出现t中的次数。

复制代码
 1 class Solution {
 2 public:
 3     string minWindow(string s, string t) {
 4         int slen=s.size();
 5         int tlen=t.size();
 6         if(tlen==0||slen<tlen) return "";
 7         int needfind[256]={0};
 8         int hasfind[256]={0};
 9         for(int i=0;i<tlen;i++)
10         {
11             needfind[t[i]]++;
12         }
13         int count=0;
14         int begin=0;
15         int end=0;
16         int minwindowsizetmp=0;
17         int minbegin=0;
18         int minend=slen-1;
19         int minwindowsize=INT_MAX;
20         for(count=0;end<slen;end++)
21         {
22             if(needfind[s[end]]==0)
23                 continue;
24             hasfind[s[end]]++;
25             if(hasfind[s[end]]<=needfind[s[end]])
26             {
27                 
28                  count++;
29             }
30                
31             if(count==tlen)
32             {
33                 while(begin<end)
34                 {
35                     if(needfind[s[begin]]==0)
36                     {
37                         begin++;
38                         continue;
39                     }
40                     if(hasfind[s[begin]]>needfind[s[begin]])
41                     {
42                         hasfind[s[begin]]--;//若该行放到begin++下边,则会出现下述错误,谨记。
43                         begin++;
44                         
45                         continue;
46                     }
47                     else 
48                         break;
49                 }
50                 minwindowsizetmp=end-begin+1;
51             
52                 if(minwindowsizetmp<minwindowsize)
53                 {
54                     minbegin=begin;
55                     minend=end;
56                     minwindowsize=minwindowsizetmp;
57                 }
58             }
59         }
60         if(minwindowsize==INT_MAX)
61           return "";
62         return s.substr(minbegin,minwindowsize);
63     }
64 };
复制代码

 

wrong answer:
Input:"ADOBECODEBANC", "ABC"
Output:"ANC"
Expected:"BANC"
posted @   鸭子船长  阅读(480)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示