/*
* Solution:
* 1. having left and right pointer for left end and right end of the current window
* 2. maintain a hashmap to remember the count each char in T left to be found
*/
public String findMinWindow(String S, String T) {
String res = "";
if (S == null || T == null || S.length() == 0 || T.length() == 0) {
return res;
}
Map<Character, Integer> hm = new HashMap<Character, Integer>();
//initialize the hashmap
for (int i = 0; i < T.length(); ++i) {
if(map.containsKey(T.charAt(i))){
map.put(T.charAt(i),map.get(T.charAt(i))+1);
}
else{
map.put(T.charAt(i),1);
}
}
int count = 0;//the current total count of all chars in T
int i = 0; // the left end of the current window
int min = S.length() + 1;//initialize the min length to be over the length
for (int j = 0; j < S.length(); ++j) {
if (hm.containsKey(S.charAt(j))) {
hm.put(S.charAt(j), hm.get(S.charAt(j)) - 1);
if (hm.get(S.charAt(j)) >= 0) {
count++;
}
while (count == T.length()) { //while we still have all the chars in the cur window
//we only need to check when the current char exist in T
if (hm.containsKey(S.charAt(i))) {
//Do 2 things:
//1. increment remaining occurrences by one
//2. if the current char cause the occurrences to be found grow over 0
// a. this is potentially a min string window
// b. decrement the count
hm.put(S.charAt(i), hm.get(S.charAt(i))+1);
if (hm.get(S.charAt(i)) > 0) {
if (min > j - i + 1) {
res = S.substring(i, j + 1);
min = j - i + 1;
}
count--;
}
}
//this is in the while loop,
// increment the left window edge when the count remains
i++;
}
}
}
return res;
}
[LinkedIn] Minimum Window Substring
最新推荐文章于 2019-04-25 05:56:00 发布