public class Solution {
public String minWindow(String s, String t) {
String result = "";
if (s == null || t == null || s.length() < t.length()) {
return result;
}
int tLen = t.length();
int left = 0;
//int right = 0;
int count = 0;
int minLen = Integer.MAX_VALUE;
Map<Character, Integer> target = new HashMap<Character, Integer>();
for (int i = 0; i < tLen; i++) {
char c = t.charAt(i);
if (target.containsKey(c)) {
target.put(c, target.get(c) + 1);
} else {
target.put(c, 1);
}
}
Map<Character, Integer> map = new HashMap<Character, Integer>();
for (int right = 0; right < s.length(); right++) {
char c = s.charAt(right);
if (target.containsKey(c)) {
if (map.containsKey(c)) {
if (map.get(c) < target.get(c)) {
count++;
}
map.put(c, map.get(c) + 1);
} else {
count++;
map.put(c, 1);
}
}
if (count == tLen) {
char prev = s.charAt(left);
while (!map.containsKey(prev) || map.get(prev) > target.get(prev)) {
if (map.containsKey(prev) && map.get(prev) > target.get(prev)) {
map.put(prev, map.get(prev) - 1);
}
left++;
prev = s.charAt(left);
}
if (right - left + 1 < minLen) {
result = s.substring(left, right + 1);
minLen = right - left + 1;
}
count--;
map.put(prev, map.get(prev) - 1);
left++;
}
}
return result;
}
}