Title description:
Give you a string s and a string t. Returns the smallest substring of s that covers all characters of t. If there is no substring in s that covers all characters of t, an empty string "" is returned.
Note: If there is such a substring in s, we guarantee that it is the only answer.
Tip:
1 <= s.length, t.length <= 105
s and t are composed of English letters
Example 1:
Input: s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"
Example 2:
Input: s = "a", t = "a"
Output: "a"
The JAVA code is as follows:
class Solution {
public String minWindow(String s, String t) {
HashMap<Character, Integer> need = new HashMap<>();
HashMap<Character, Integer> window = new HashMap<>();
int left = 0, right = 0;
int valid = 0;
int start = 0, len = Integer.MAX_VALUE;
for (char ch : t.toCharArray()) {
need.put(ch, need.getOrDefault(ch, 0) + 1);//计算t中字符出现的个数
}
while (right < s.length()) {
char c = s.charAt(right);
right++;
if (need.containsKey(c)) {
window.put(c, window.getOrDefault(c, 0) + 1);
if (window.get(c).equals(need.get(c))) {
valid++;
}
}
while (valid == need.size()) {
if (right - left < len) {
start = left;
len = right - left;
}
char d = s.charAt(left);
left++;
if (need.containsKey(d)) {
if (window.get(d).equals(need.get(d))) {
valid--;
}
window.put(d, window.getOrDefault(d, 0) - 1);
}
}
}
return len == Integer.MAX_VALUE ? "" : s.substring(start, start + len);
}
}
Results of the: