forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0076-minimum-window-substring.cs
60 lines (49 loc) · 1.56 KB
/
0076-minimum-window-substring.cs
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
55
56
57
58
59
60
publicclassSolution
{
publicstringMinWindow(strings,stringt)
{
if(string.IsNullOrEmpty(t))returnstring.Empty;
varcountT=newDictionary<char,int>();
varwindow=newDictionary<char,int>();
foreach(varcint)
{
AddCharToDictionary(c,countT);
}
varhave=0;
varneed=countT.Count;
varleft=0;
varres=new[]{-1,-1};
varresultLength=int.MaxValue;
for(varright=0;right<s.Length;right++)
{
varc=s[right];
AddCharToDictionary(c,window);
if(countT.ContainsKey(c)&&window[c]==countT[c])have++;
while(have==need)
{
// update our result
varwindowSize=right-left+1;
if(windowSize<resultLength)
{
res=new[]{left,right};
resultLength=windowSize;
}
// pop from the left of our window
window[s[left]]--;
if(countT.ContainsKey(s[left])&&window[s[left]]<countT[s[left]])
{
have--;
}
left++;
}
}
returnresultLength==int.MaxValue
?string.Empty
:s.Substring(res[0],res[1]-res[0]+1);
}
privatevoidAddCharToDictionary(charc,IDictionary<char,int>dict)
{
if(dict.ContainsKey(c))dict[c]++;
elsedict.Add(c,1);
}
}