-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinimumWindowContiguousSubString.java
More file actions
60 lines (47 loc) · 1.6 KB
/
MinimumWindowContiguousSubString.java
File metadata and controls
60 lines (47 loc) · 1.6 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
*
* Given strings S and T, find the minimum (contiguous) substring W of S, so that T is a subsequence of W.
If there is no such window in S that covers all characters in T, return the empty string "". If there are multiple such minimum-length windows, return the one with the left-most starting index.
Example 1:
Input:
S = "abcdebdde", T = "bde"
Output: "bcde"
Explanation:
"bcde" is the answer because it occurs before "bdde" which has the same length.
"deb" is not a smaller window because the elements of T in the window must occur in order.
Note:
All the strings in the input will only contain lowercase letters.
The length of S will be in the range [1, 20000].
The length of T will be in the range [1, 100].
*/
public class MinimumWindowContiguousSubString {
public static void main(String[] args) {
System.out.println(new MinimumWindowContiguousSubString().minWindow("cnhczmccqouqadqtmjjzl", "mm"));
}
public String minWindow(String S, String T) {
if (S == null || S.length() <= 0 || T == null || T.length() <= 0) {
return "";
}
char[] s = S.toCharArray(), t = T.toCharArray();
int sindex = 0, tindex = 0, slen = s.length, tlen = t.length, start = -1, len = slen;
while (sindex < slen) {
if (s[sindex] == t[tindex]) {
tindex++;
if (tindex == tlen) {
int end = sindex + 1;
while (--tindex >= 0) {
while (s[sindex--] != t[tindex]);
}
if (len > end - sindex) {
len = end - sindex;
start = sindex;
}
tindex++;
sindex++;
}
}
sindex++;
}
return start == -1 ? "" : S.substring(start, start + len);
}
}