Given a string source and a string target, find the minimum window in source which will contain all the characters in target.windows
If there is no such window in source that covers all characters in target, return the emtpy string ""
.spa
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in source.指針
Should the characters in minimum window has the same order in target?code
For source = "ADOBECODEBANC"
, target = "ABC"
, the minimum window is"BANC"
blog
1 class Solution { 2 public String minWindow(String source , String target) { 3 if (source == null || target == null || source.length() < target.length()) return ""; 4 5 Map<Character, Integer> map = new HashMap<>(); 6 String minString = source + " "; 7 int count = target.length(), start = 0; 8 9 for (int i = 0; i < target.length(); i++) { 10 map.put(target.charAt(i), map.getOrDefault(target.charAt(i), 0) + 1); 11 } 12 13 for (int i = 0; i < source.length(); i++) { 14 if (map.containsKey(source.charAt(i))) { 15 int occurences = map.get(source.charAt(i)); 16 if (occurences > 0) { 17 count--; 18 } 19 map.put(source.charAt(i), occurences - 1); 20 } 21 // decrease the window size 22 while (count == 0 && map.getOrDefault(source.charAt(start), -1) < 0) { 23 if (map.containsKey(source.charAt(start))) { 24 map.put(source.charAt(start), map.get(source.charAt(start)) + 1); 25 } 26 start++; 27 } 28 29 if (count == 0 && i - start + 1 < minString.length()) { 30 minString = source.substring(start, i + 1); 31 } 32 } 33 return minString.length() <= source.length() ? minString : ""; 34 } 35 }