LeetCode - Minimum Window Substring

1 minute read

Problem description

description

Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).

Example:

1
2
Input: S = "ADOBECODEBANC", T = "ABC"
Output: "BANC"

Note:

  • If there is no such window in S that covers all characters in T, return the empty string “”.
  • If there is such window, you are guaranteed that there will always be only one unique minimum window in S.

Analysis

Generally, it’s a typical sliding window problem.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Solution {
    public String minWindow(String s, String t) {
        HashMap<Character, Integer> map = new HashMap<>();
        
        for (char c:t.toCharArray()){
            map.put(c, map.getOrDefault(c, 0)  +1);
        }
        
        int end = 0;
        String res = "";
        int start = 0;
        
        while (end < s.length()){
            char c = s.charAt(end);
            
            if (map.containsKey(c)){
                map.put(c, map.get(c) - 1);
            }
            
            end++;
            
            while (check(map) && start <= end){
                String r = s.substring(start, end);
                
                if (r.length() < res.length() || res.length() == 0){
                    res = r;
                }
                    
                char c2 = s.charAt(start);
                if (map.containsKey(c2)){
                    map.put(c2, map.get(c2) + 1);
                }
                start++;
            }
        }
        
        return res;
    }
    
    boolean check(HashMap<Character, Integer> map){
        for (Map.Entry<Character, Integer> entry: map.entrySet()){
            if (entry.getValue() > 0){
                return false;
            }
        }
        
        return true;
    }
}

What to improve

  • should be more familiar with the template of sliding window.