Skip to content

Commit 78216d7

Browse files
authored
76. Minimum Window Substring
1 parent c61d805 commit 78216d7

File tree

1 file changed

+18
-27
lines changed

1 file changed

+18
-27
lines changed
Lines changed: 18 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,28 @@
11
class Solution {
22
public:
3-
string minWindow(string S, string T) {
4-
if (S.empty() || T.empty()) return "";
5-
int needed(T.size());
6-
int require[128] = {0};
7-
for (int i = 0; i < needed; ++i) {
8-
require[T[i]]++;
3+
string minWindow(string s, string t) {
4+
unordered_map<char, int> dict;
5+
int cnt = 0, start = 0, len = INT_MAX, first = 0;
6+
for (char c : t) {
7+
dict[c]++;
98
}
10-
int left(0), right(-1);
11-
int minLen(INT_MAX), minIdx(0);
12-
while (right < (int)S.size()) {
13-
if (needed) {
14-
char ch = S[++right];
15-
require[ch]--;
16-
if (require[ch] >= 0) {
17-
needed--;
18-
}
9+
for (int i = 0; i < s.size(); i++) {
10+
dict[s[i]]--;
11+
if (dict[s[i]] >= 0) {
12+
cnt++;
1913
}
20-
else {
21-
char ch = S[left];
22-
int temp_length = right-left+1;
23-
if (minLen > temp_length) {
24-
minLen = temp_length;
25-
minIdx = left;
14+
while (cnt == t.size()) {
15+
dict[s[start]]++;
16+
if (dict[s[start]] > 0) {
17+
cnt--;
2618
}
27-
require[ch]++;
28-
if (require[ch] > 0) {
29-
needed++;
19+
if (i - start + 1 < len) {
20+
len = i - start + 1;
21+
first = start;
3022
}
31-
left++;
23+
start++;
3224
}
3325
}
34-
if (minLen == INT_MAX) return "";
35-
return S.substr(minIdx, minLen);
26+
return len == INT_MAX ? "" : s.substr(first, len);
3627
}
3728
};

0 commit comments

Comments
 (0)