-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathMinimumWindowSubstring.java
More file actions
38 lines (31 loc) · 993 Bytes
/
MinimumWindowSubstring.java
File metadata and controls
38 lines (31 loc) · 993 Bytes
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
/*
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).
Example:
Input: S = "ADOBECODEBANC", T = "ABC"
Output: "BANC"
*/
class Solution {
public String minWindow(String s, String t) {
HashMap<Character,Integer> hm = new HashMap<>();
for(int i=0;i<t.length();i++){
char ch = t.charAt(i);
hm.put(ch,hm.getOrDefault(ch,0)+1);
}
int missing=hm.size();
int left=0,l=0,r=Integer.MAX_VALUE;
while(missing==0){
if(i-left<r-l){
l=left;
r=i;
}
char temp = s.charAt(left++);
if(hm.containsKey(temp)){
if(hm.get(temp)==0)
missing+=1;
hm.put(temp,hm.get(temp)+1);
}
}
}
return r==Integer.MAX_VALUE ? "" : s.substring(l,r+1);
}
}