Skip to content

Commit 1fe589b

Browse files
committed
76. Minimum Window Substring
1 parent 923da4e commit 1fe589b

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
public class Solution
2+
{
3+
4+
public string MinWindow(string s, string t)
5+
6+
{
7+
if (string.IsNullOrEmpty(t)) return string.Empty;
8+
9+
var countT = new Dictionary<char, int>();
10+
var window = new Dictionary<char, int>();
11+
12+
foreach (var c in t)
13+
{
14+
AddCharToDictionary(c, countT);
15+
}
16+
17+
var have = 0;
18+
var need = countT.Count;
19+
var left = 0;
20+
var res = new[] { -1, -1 };
21+
var resultLength = int.MaxValue;
22+
for (var right = 0; right < s.Length; right++)
23+
{
24+
var c = s[right];
25+
AddCharToDictionary(c, window);
26+
27+
if (countT.ContainsKey(c) && window[c] == countT[c]) have++;
28+
29+
while (have == need)
30+
{
31+
// update our result
32+
var windowSize = right - left + 1;
33+
if (windowSize < resultLength)
34+
{
35+
res = new[] { left, right };
36+
resultLength = windowSize;
37+
}
38+
39+
// pop from the left of our window
40+
window[s[left]]--;
41+
if (countT.ContainsKey(s[left]) && window[s[left]] < countT[s[left]])
42+
{
43+
have--;
44+
}
45+
46+
left++;
47+
}
48+
}
49+
50+
return resultLength == int.MaxValue
51+
? string.Empty
52+
: s.Substring(res[0], res[1] - res[0] + 1);
53+
}
54+
55+
private void AddCharToDictionary(char c, IDictionary<char, int> dict)
56+
{
57+
if (dict.ContainsKey(c)) dict[c]++;
58+
else dict.Add(c, 1);
59+
}
60+
}

0 commit comments

Comments
 (0)