-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMin_window.java
More file actions
46 lines (36 loc) · 1.04 KB
/
Min_window.java
File metadata and controls
46 lines (36 loc) · 1.04 KB
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
public class Min_window {
public String minWindow(String s1, String s2) {
int n = s1.length(), m = s2.length();
int minLen = Integer.MAX_VALUE;
int startIndex = -1;
int i = 0;
while (i < n) {
int j = 0;
// ✅ FIXED forward scan
while (i < n && j < m) {
if (s1.charAt(i) == s2.charAt(j)) {
j++;
}
i++;
}
if (j < m) break;
// Backward shrink
int end = i - 1;
j = m - 1;
while (j >= 0) {
if (s1.charAt(i - 1) == s2.charAt(j)) {
j--;
}
i--;
}
int start = i;
if (end - start + 1 < minLen) {
minLen = end - start + 1;
startIndex = start;
}
i = start + 1; // reset
}
return startIndex == -1 ? "" :
s1.substring(startIndex, startIndex + minLen);
}
}