76 Minimum Window Substring

1. Question

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.

2. Implementation

(1) Two Pointer + Hash
1
class Solution {
2
public String minWindow(String s, String t) {
3
int[] map = new int[256];
4
int count = t.length();
5
int minLen = Integer.MAX_VALUE;
6
int minStart = 0, minEnd = 0, start = 0 , end = 0;
7
8
for (char c : t.toCharArray()) {
9
++map[c];
10
}
11
12
while (end < s.length()) {
13
if (map[s.charAt(end)] >= 1) {
14
--count;
15
}
16
--map[s.charAt(end)];
17
++end;
18
19
while (count == 0) {
20
if (end - start < minLen) {
21
minEnd = end;
22
minStart = start;
23
minLen = end - start;
24
}
25
26
if (map[s.charAt(start)] >= 0) {
27
++count;
28
}
29
++map[s.charAt(start)];
30
++start;
31
}
32
}
33
return minLen == Integer.MAX_VALUE ? "" : s.substring(minStart, minEnd);
34
}
35
}
Copied!

3. Time & Space Complexity

(1) Two Pointer + Hash: 时间复杂度O(n), 空间复杂度O(1)