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
| class Solution {
public String minWindow(String s, String t) {
int m = s.length(), n = t.length();
if (n > m) return "";
int[] need = new int[128];
for (int i = 0; i < n; i ++) {
need[t.charAt(i)] ++;
}
int missing = n;
int bestLen = Integer.MAX_VALUE;
int bestL = 0;
int l = 0;
for (int r = 0; r < m; r ++) {
char c = s.charAt(r);
if (need[c] > 0) {
missing--;
}
need[c]--;
while(missing == 0) {
int len = r - l + 1;
if (len < bestLen) {
bestLen = len;
bestL = l;
}
char leftChar = s.charAt(l);
need[leftChar]++;
if (need[leftChar] > 0) {
missing ++;
}
l ++;
}
}
return bestLen == Integer.MAX_VALUE ? "" : s.substring(bestL, bestL + bestLen);
}
}
|