-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathminWindowSubstring.java
More file actions
54 lines (53 loc) · 1.92 KB
/
minWindowSubstring.java
File metadata and controls
54 lines (53 loc) · 1.92 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
import java.util.*;
public class minWindowSubstring {
public static void main(String[] args){
minWindowSubstring obj = new minWindowSubstring();
String s = "cabwefgewcwaefgcf";
String t = "cae";
System.out.println(obj.minWindow(s,t));
}
/* 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).
Input: S = "ADOBECODEBANC", T = "ABC"
Output: "BANC"
* */
// two pointers, sliding window algorithm
private String minWindow(String s, String t){
String res = "";
if(s == null || t == null || s.length() < t.length()){
return res;
}
int min = s.length();
Map<Character, Integer> map = new HashMap<>();
for(char ele: t.toCharArray()){
map.put(ele, map.getOrDefault(ele,0)+1);
}
int counter = map.size();
//int lo = 0, hi = 0;
for(int lo=0, hi=0; hi < s.length(); hi ++){
// move right pointer to find a valid substring
if(map.containsKey(s.charAt(hi))){
map.put(s.charAt(hi),map.get(s.charAt(hi)) - 1);
if(map.get(s.charAt(hi)) == 0){
counter --;
}
}
// move left pointer to find a min substring
while(counter == 0 && lo <= hi){
// pay attention to "<="
// don't forget to update min's valueß
if(hi - lo + 1 <= min){
res = s.substring(lo, hi+1);
min = hi - lo + 1;
}
if(map.containsKey(s.charAt(lo))){
map.put(s.charAt(lo), map.get(s.charAt(lo)) + 1);
if(map.get(s.charAt(lo)) > 0){
counter ++;
}
}
lo ++;
}
}
return res;
}
}