Skip to content

Commit 8cf609f

Browse files
committed
refine
1 parent d71d3b2 commit 8cf609f

File tree

1 file changed

+32
-42
lines changed

1 file changed

+32
-42
lines changed

MinimumWindowSubstring.java

Lines changed: 32 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -15,49 +15,39 @@
1515

1616
public class MinimumWindowSubstring {
1717
public String minWindow(String S, String T) {
18-
int sLen = S.length();
19-
int tLen = T.length();
20-
int[] needToFind = new int[256];
21-
22-
for (int i = 0; i < tLen; i++)
23-
needToFind[T.charAt(i)]++;
24-
2518
int[] hasFound = new int[256];
26-
int minWindowLen = Integer.MAX_VALUE;
27-
int minWindowBegin = 0;
28-
int minWindowEnd = 0;
29-
int count = 0;
30-
for (int begin = 0, end = 0; end < sLen; end++) {
31-
// skip characters not in T
32-
if (needToFind[S.charAt(end)] == 0)
33-
continue;
34-
hasFound[S.charAt(end)]++;
35-
if (hasFound[S.charAt(end)] <= needToFind[S.charAt(end)])
36-
count++;
37-
38-
// if window constraint is satisfied
39-
if (count == tLen) {
40-
// advance begin index as far right as possible,
41-
// stop when advancing breaks window constraint.
42-
while (needToFind[S.charAt(begin)] == 0
43-
|| hasFound[S.charAt(begin)] > needToFind[S
44-
.charAt(begin)]) {
45-
if (hasFound[S.charAt(begin)] > needToFind[S.charAt(begin)])
46-
hasFound[S.charAt(begin)]--;
47-
begin++;
19+
int[] needFound = new int[256];
20+
int diffCount = T.length();
21+
int length = S.length();
22+
String window = "";
23+
int size = Integer.MAX_VALUE;
24+
if (length == 0 || diffCount == 0)
25+
return window;
26+
for (int l = 0; l < diffCount; l++) {
27+
needFound[T.charAt(l)]++;
28+
}
29+
int i = 0, j = 0;
30+
while (j < length) {
31+
char c = S.charAt(j);
32+
if (needFound[c] > 0 && ++hasFound[c] <= needFound[c]) {
33+
diffCount--;
34+
}
35+
if (diffCount == 0) {
36+
while (i <= j) {
37+
char h = S.charAt(i);
38+
i++;
39+
if (needFound[h] > 0 && --hasFound[h] < needFound[h]) {
40+
if (j - i + 1 < size) {
41+
size = j - i + 1;
42+
window = S.substring(i - 1, j + 1);
43+
}
44+
diffCount++;
45+
break;
46+
}
4847
}
49-
50-
// update minWindow if a minimum length is met
51-
int windowLen = end - begin + 1;
52-
if (windowLen < minWindowLen) {
53-
minWindowBegin = begin;
54-
minWindowEnd = end;
55-
minWindowLen = windowLen;
56-
} // end if
57-
} // end if
58-
} // end for
59-
60-
return (count == tLen) ? S.substring(minWindowBegin, minWindowEnd + 1)
61-
: "";
48+
}
49+
j++;
50+
}
51+
return window;
6252
}
6353
}

0 commit comments

Comments
 (0)