-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathminimum window substrings.cpp
59 lines (49 loc) · 1.45 KB
/
minimum window substrings.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
55
56
57
58
59
class Solution
{
public:
string minWindow(string s, string t)
{
int n = s.length();
if (t.length() > n)
return "";
string ans;
unordered_map<char, int> charCount;
for (char &c : t)
{
charCount[c]++;
}
int requiredCount = t.length();
int i = 0, j = 0;
int minWindowSize = INT_MAX;
int startInd = 0;
while (j < n)
{
char ch = s[j];
if (charCount[ch] > 0)
{
requiredCount--;
}
// always reduce map frequency
charCount[ch]--;
while (requiredCount == 0)
{
// start shrinking the window
int currWindowSize = j - i + 1;
if (minWindowSize > currWindowSize)
{
minWindowSize = currWindowSize;
startInd = i;
}
charCount[s[i]]++;
if (charCount[s[i]] > 0)
{
requiredCount++;
}
i++;
}
j++;
}
return minWindowSize == INT_MAX ? "" : s.substr(startInd, minWindowSize);
}
};
// leetcode - 76