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.windows

 Notice

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.指針

Clarification

Should the characters in minimum window has the same order in target?code

  • Not necessary.
Example

For source = "ADOBECODEBANC", target = "ABC", the minimum window is"BANC"blog

分析:
用兩個指針,start, i. 咱們首先移動i,使得start 和i中間部分可以徹底cover target,當咱們移動i,再次找到一個target中含有的character,咱們就看是否能夠移動start,使得start和i之間的距離變小,並且仍是可以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         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 }
相關文章
相關標籤/搜索