LeetCode: Minimum Window Substring

LeetCode: Minimum Window 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

/**
* Description: For example,
* <p/>
* S = "ADOBECODEBANC"
* <p/>
* T = "ABC"
* <p/>
* Minimum window is "BANC".
*
* @author hzhou
*/
public class MinimumWindowSubstring {
public String minWindow(String s, String t) {
if (t == null || t.isEmpty()) {
return "";
}
if (s == null || s.isEmpty()) {
return null;
}
Map<Character, Integer> tMap = new HashMap<Character, Integer>();
for (int i = 0; i < t.length(); i++) {
char c = t.charAt(i);
if (tMap.containsKey(c)) {
tMap.put(c, tMap.get(c) + 1);
} else {
tMap.put(c, 1);
}
}
Map<Character, Integer> countMap = new HashMap<Character, Integer>();
int matchCount = 0;
int start = 0;
String min = "";
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (tMap.containsKey(c)) {
if (countMap.containsKey(c)) {
if (countMap.get(c) < tMap.get(c)) {
matchCount++;
}
countMap.put(c, countMap.get(c) + 1);
} else {
countMap.put(c, 1);
matchCount++;
}
}
if (matchCount == t.length()) {
char tmp = s.charAt(start);
while (start < s.length() && (!countMap.containsKey(tmp) || countMap.get(tmp) > tMap.get(tmp))) {
if (countMap.containsKey(tmp)) {
countMap.put(tmp, countMap.get(tmp) - 1);
}
start++;
tmp = s.charAt(start);
}
if (min.isEmpty() || i + 1 - start < min.length()) {
min = s.substring(start, i + 1);
}
}
}
return min;
}
@Test
public void test() {
String s = "a";
String t = "aa";
String result = minWindow(s, t);
}
}