-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathminimum window substring.cpp
54 lines (52 loc) · 1.15 KB
/
minimum window substring.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Solution {
public:
string minWindow(string s, string t) {
int n=s.length();
int m=t.length();
unordered_map<char,int> mp;
for(int i=0;i<m;i++)
{
mp[t[i]]++;
}
unordered_map<char,int> w;
int l=0;
int h=0;
int id1=-1, id2=-1;
int res=INT_MAX;
while(h<n)
{
w[s[h]]++;
bool flag=true;
for(auto it:mp)
{
if(it.second>w[it.first])
{
flag=false;
break;
}
}
if(flag==false)
{
h++;
continue;
}
while(l<=h && w[s[l]]-1>=mp[s[l]])
{
w[s[l]]--;
l++;
}
if(l>h)
continue;
if(res>h-l+2)
{
id1=l;
id2=h;
res=h-l+2;
}
h++;
}
if(id1==-1 && id2==-1)
return "";
return s.substr(id1,id2-id1+1);
}
};