Minimum Window Substring

本文介绍了一种复杂度为O(n)的算法,用于在给定字符串中查找最短的子串,该子串包含另一个字符串的所有字符。通过使用双指针技巧,该算法在实践中表现出高效性,尤其适用于处理大规模数据集。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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"

转载于:https://www.cnblogs.com/zl1991/p/4704807.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值