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, i. 我们首先移动i,使得start 和i中间部分能够完全cover target,当我们移动i,再次找到一个target中含有的character,我们就看是否可以移动start,使得start和i之间的距离变小,而且还是能够cover target中的所有字符。如果可以,那么我们就保存。
1 public class Solution { 2 public String minWindow(String source, String target) { 3 if (source == null || target == null || source.length() < target.length()) return ""; 4 5 int count = 0, start = 0; 6 int[] targetCharCounts = new int[256]; 7 int[] allAppeared = new int[256]; 8 9 String minString = source + " "; 10 11 for (int i = 0; i < target.length(); i++) { 12 targetCharCounts[target.charAt(i)]++; 13 } 14 15 for (int i = 0; i < source.length(); i++) { 16 allAppeared[source.charAt(i)]++; 17 if (targetCharCounts[source.charAt(i)] >= allAppeared[source.charAt(i)]) { 18 count++; 19 } 20 // decrease the window size 21 while (count == target.length() && start < source.length() && allAppeared[source.charAt(start)] > targetCharCounts[source.charAt(start)]) { 22 allAppeared[source.charAt(start)]--; 23 start++; 24 } 25 26 if (count == target.length() && i - start + 1 < minString.length()) { 27 minString = source.substring(start, i + 1); 28 } 29 } 30 return minString.length() <= source.length() ? minString : ""; 31 } 32 }
Using HashMap
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 = 0, 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 == target.length() && 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 == target.length() && i - start + 1 < minString.length()) { 30 minString = source.substring(start, i + 1); 31 } 32 } 33 return minString.length() <= source.length() ? minString : ""; 34 } 35 }