-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path76-minimum-window-substring.cs
59 lines (48 loc) · 1.27 KB
/
76-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
public class Solution {
public string MinWindow(string s, string t)
{
var expected = new int[52];
foreach (var ch in t)
{
expected[Hash(ch)]++;
}
var count = new int[52];
int behind = expected.Count(e => e > 0), start = 0, end = -1;
int ri = -1, rj = -1;
while (start < s.Length)
{
var hash = -1;
while (behind > 0 && end < s.Length - 1)
{
end++;
hash = Hash(s[end]);
count[hash]++;
if (count[hash] == expected[hash])
{
behind--;
}
}
if (behind == 0 && (ri == - 1 || end - start < rj - ri))
{
ri = start;
rj = end;
}
hash = Hash(s[start]);
count[hash]--;
if (count[hash] == expected[hash] - 1)
{
behind++;
}
start++;
}
return ri == - 1 ? string.Empty : s.Substring(ri, rj - ri + 1);
}
private static int Hash(char ch)
{
if (char.IsUpper(ch))
{
return ch - 'A';
}
return ch - 'a' + 26;
}
}