1
1
class Solution {
2
2
public:
3
3
string minWindow (string S, string T) {
4
- // Start typing your C/C++ solution below
5
- // DO NOT write int main() function
6
-
7
- int needFind[256 ] = {0 };
8
- int hasFound[256 ] = {0 };
9
- int count = 0 , minLen = INT_MAX;
10
- string result = " " ;
11
-
12
- for (int i = 0 ; i < T.size (); i++)
13
- needFind[T[i]] += 1 ;
14
-
15
- for (int low = 0 , high = 0 ; high < S.size (); high++) {
16
- if (needFind[S[high]] == 0 )
4
+ string result (" " );
5
+ map<char , int > needed;
6
+ map<char , int > found;
7
+ for (int i = 0 ; i < T.size (); i++) {
8
+ needed[T[i]]++;
9
+ }
10
+ int count = 0 ;
11
+ int minlen = S.size () + 1 ;
12
+ for (int i = 0 , j = 0 ; j < S.size (); j++) {
13
+ if (needed[S[j]] == 0 ) {
17
14
continue ;
18
-
19
- hasFound [S[high]] += 1 ;
20
- if (hasFound [S[high ]] <= needFind [S[high ]])
21
- count += 1 ;
22
-
15
+ }
16
+ found [S[j]]++ ;
17
+ if (found [S[j ]] <= needed [S[j ]]) {
18
+ count++ ;
19
+ }
23
20
if (count == T.size ()) {
24
- while (low < high) {
25
- if (needFind[S[low]] == 0 ) {
26
- low += 1 ;
27
- continue ;
28
- }
29
- if (hasFound[S[low]] > needFind[S[low]])
30
- hasFound[S[low]] -= 1 ;
31
- else
21
+ while (i <= j) {
22
+ if (found[S[i]] == 0 ) {
23
+ i++;
24
+ } else if (found[S[i]] > needed[S[i]]) {
25
+ found[S[i]]--;
26
+ i++;
27
+ } else {
32
28
break ;
33
- low += 1 ;
29
+ }
34
30
}
35
- if (minLen > high - low + 1 ) {
36
- minLen = high - low + 1 ;
37
- result = S.substr (low, minLen );
31
+ if (minlen > j - i + 1 ) {
32
+ minlen = j - i + 1 ;
33
+ result = S.substr (i, minlen );
54F5
38
34
}
39
35
}
40
36
}
41
37
return result;
42
38
}
43
- };
39
+ };
0 commit comments