76. Minimum Window Substring
Given a string source and a string target, find the minimum window in source which will contain all the characters in target.
Notice
If there is no such window in source that covers all characters in target, return the emtpy string ""
.
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in source.
Clarification
Should the characters in minimum window has the same order in target?
- Not necessary.
Example
For source = "ADOBECODEBANC"
, target = "ABC"
, the minimum window is"BANC"
分析:
用两个指针,start, end 我们首先移动end,使得start 和end中间部分能够完全cover target,我们就可以移动start,使得start和end之间的距离变小,而且还是能够cover target中的所有字符。
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 8 for (char ch : target.toCharArray()) { 9 map.put(ch, map.getOrDefault(ch, 0) + 1); 10 } 11 12 int count = 0, start = 0, end = 0; 13 while (end < source.length()) { 14 char endLetter = source.charAt(end); 15 if (map.containsKey(endLetter)) { 16 if (map.get(endLetter) > 0) { 17 count++; 18 } 19 map.put(endLetter, map.get(endLetter) - 1); 20 } 21 end++; 22 // decrease the window size 23 while (count == target.length()) { 24 if (end - start < minString.length()) { 25 minString = source.substring(start, end); 26 } 27 char letter = source.charAt(start); 28 if (map.containsKey(letter)) { 29 if (map.get(letter) == 0) { 30 count--; 31 } 32 map.put(letter, map.get(letter) + 1); 33 } 34 start++; 35 } 36 } 37 return minString.length() <= source.length() ? minString : ""; 38 } 39 }