forked from gouthampradhan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinimumWindowSubstring.java
More file actions
84 lines (72 loc) · 2.27 KB
/
MinimumWindowSubstring.java
File metadata and controls
84 lines (72 loc) · 2.27 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package two_pointers;
/**
* Created by gouthamvidyapradhan on 03/12/2017.
*
* Given a string S and a string T, find the minimum window in S which will contain all the characters in
* T in complexity O(n).
For example,
S = "ADOBECODEBANC"
T = "ABC"
Minimum window is "BANC".
Note:
If there is no such window in S that covers all characters in T, return the empty string "".
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
Solution O(n). Sliding window sub-sting using two pointers.
*/
public class MinimumWindowSubstring {
private int[] hash = new int[256];
private int[] curr = new int[256];
/**
* Main method
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception{
System.out.println(new MinimumWindowSubstring().minWindow("ADOBECODEBANC", "ABC"));
}
public String minWindow(String s, String t) {
if(s.isEmpty() && t.isEmpty()) return "";
if(t.length() > s.length()) return "";
int start = -1, end = -1, min = Integer.MAX_VALUE;
for(int i = 0, l = t.length(); i < l; i ++){
hash[t.charAt(i)]++;
}
for(int i = 0, l = t.length() - 1; i < l; i ++){
curr[s.charAt(i)]++;
}
for(int i = 0, j = t.length() - 1, l = s.length(); j < l;){
curr[s.charAt(j)]++;
if(isMatch()){
if(j - i < min){
min = j - i;
start = i;
end = j;
}
while(j > i){
curr[s.charAt(i)]--;
i ++;
if(isMatch()){
if(j - i < min){
min = j - i;
start = i;
end = j;
}
} else break;
}
}
j ++;
}
if(min == Integer.MAX_VALUE){
return "";
}
return s.substring(start, end + 1);
}
private boolean isMatch(){
for(int i = 0; i < 256; i ++){
if(curr[i] < hash[i]){
return false;
}
}
return true;
}
}