-
Notifications
You must be signed in to change notification settings - Fork 0
/
Minimum Window Substring.cpp
50 lines (47 loc) · 1.4 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
#include <iostream>
#include <unordered_map>
class Solution {
public:
std::string minWindow(std::string s, std::string t) {
std::unordered_map<char, int> count;
for (char c : t) {
count[c]++;
}
int matchedChars = 0;
int lowestLength = INT_MAX;
int bestLeft = -1;
int bestRight = -1;
int left = 0;
int right = 0;
while (right < s.size()) {
char c = s[right];
count[c]--;
if (count[c] >= 0) {
matchedChars++;
}
if (matchedChars == t.size() && right - left + 1 <= lowestLength) {
lowestLength = right - left + 1;
bestLeft = left;
bestRight = right;
}
while (matchedChars == t.size() && left < right) {
count[s[left]]++;
if (count[s[left]] > 0) {
matchedChars--;
}
left++;
if (matchedChars == t.size() &&
right - left + 1 <= lowestLength) {
lowestLength = right - left + 1;
bestLeft = left;
bestRight = right;
}
}
right++;
}
if (bestLeft == -1) {
return "";
}
return s.substr(bestLeft, bestRight - bestLeft + 1);
}
};