leetcode-76 最小覆盖子串

题目描述:给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 ""

代码实现

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
class Solution {
public String minWindow(String s, String t) {
Map<Character, Integer> need = new HashMap<>();
Map<Character, Integer> window = new HashMap<>();
for (int i = 0; i < t.length(); i++) {
need.merge(t.charAt(i), 1, (oldVal, newVal) -> ++oldVal);
}

int left = 0, right = 0, start = 0, valid = 0, len = s.length() + 1;

while (right < s.length()) {
char c = s.charAt(right);
right++;
if (need.containsKey(c)) {
window.merge(c, 1, (oldVal, newVal) -> ++oldVal);
if (need.get(c).equals(window.get(c))) {
valid++;
}
}
while (valid == need.size()) {
if (right - left < len) {
start = left;
len = right - left;
}
char l = s.charAt(left);
left++;
if (need.containsKey(l)) {
if (window.get(l).equals(need.get(l))) {
valid--;
}
window.compute(l, (k, v) -> --v);
}
}
}
return len == s.length() + 1 ? "" : s.substring(start, start + len);
}
}