76. Minimum Window Substring

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

For example,
S = “ADOBECODEBANC”
T = “ABC”
Minimum window is “BANC”.

Note:
If there is no such window in S that covers all characters in T, return the empty string “”.

If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.

解法1: Sliding Window

直接用Sliding Window的模板来做。维护一个map来存每一个字符出现的次数,用一个指针start记录substring的左边界然后遍历就可以了。

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
50
51
52
53
class Solution {
public String minWindow(String s, String t) {
// sliding window problem
if (t == null || t.length() == 0) {
return "";
}
if (s == null || s.length() == 0) {
return "";
}
//
Map<Character, Integer> map = new HashMap<>();
for (char ch : t.toCharArray()) {
map.put(ch, map.getOrDefault(ch, 0) + 1);
}
int count = t.length();
int start = 0;
int minLen = Integer.MAX_VALUE;
String res = "";
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (map.containsKey(ch)) {
map.put(ch, map.get(ch) - 1); // decrease by one
if (map.get(ch) >= 0) {
count--;
}
while (count == 0) {
// update result string
int len = i - start + 1;
if (len < minLen) {
minLen = len;
res = s.substring(start, i + 1);
}
char temp = s.charAt(start);
if (map.containsKey(temp)) {
map.put(temp, map.get(temp) + 1);
if (map.get(temp) > 0) {
count++;
}
}
start++; // move start
}
}
}
return res;
}
}