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".
//we need to find smallest substring from str1 if all character of str2 available in substring
public class MinimumWindowSubstring {
public static void main(String[] args) {
String str1 = "dbaecbbabdcaafbddcabgba";
String str2 = "abbcdc";
// String str1 = "a";
//String str2 = "aa";
int i = -1;
int j = -1;
//preparing a frequncy map of string 2
Map<Character,Integer> map2 = new HashMap<>();
for(int k = 0;k<str2.length();k++){
char ch = str2.charAt(k);
map2.put(ch, map2.getOrDefault(ch,0)+1);
}
Map<Character,Integer> map1 = new HashMap<>();
int mCount = 0;
int desireCount = str2.length();
String result = "";
while (true){
boolean f1 = false,f2 = false;
//we need to run till my current count less then desired count(str2 count)
while (i<str1.length()-1 && mCount<desireCount ){
i++;
char ch = str1.charAt(i);
map1.put(ch,map1.getOrDefault(ch,0)+1);
if(map1.getOrDefault(ch,0)<=map2.getOrDefault(ch,0)){
mCount++;
}
f1 = true;
}
//we need to run this till we are getting my current count equal to desired count
while (j<i && mCount==desireCount) {
f2 = true;
j++;
String potentialAns = str1.substring(j,i+1);
if(result.length()==0 || potentialAns.length()<result.length()){
result = potentialAns;
}
char ch = str1.charAt(j);
Integer val = map1.get(ch);
if(val>1){
map1.put(ch,map1.get(ch)-1);
}else{
map1.remove(ch);
}
if(map1.getOrDefault(ch,0)<map2.getOrDefault(ch,0)){
mCount--;
}
f2 = true;
}
if(!f1 && !f2){
break;
}
}
System.out.println(result);
}
}
Result: cbbabdc
No comments:
Post a Comment