LeetCode 76题 -> 最小覆盖子串
1. 题目描述
-
给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 “” 。
-
示例:
输入:s = "ADOBECODEBANC", t = "ABC" 输出:"BANC"
2. 解题思路
- 滑动窗口
- ①在字符串s中使用左右指针,初始化 left = 0,right = 0。[left, right)即为一个窗口;
- ②right指针向右扩大窗口,即right++,直到窗口中的字符串包含了t中所有字符;(可行解)
- ③此时,right指针暂停移动,开始尝试增加left指针缩小窗口,直到窗口中的字符串不包含t中所有字符;同时,每次增加left,更新滑动窗口的大小;(优化解)
- ④重复②③,直到right达到字符串s的尽头。
3. 代码实现
import java.util.HashMap;
import java.util.Map;
public class MinWindow {
public static String minWindow(String s, String t){
if(s == null || t == null || s.length() < t.length()){
return "";
}
//needs存放字符串t的<字符,字符出现次数>
Map<Character,Integer> needs = new HashMap<>();
//window中存放<s中与t中字符相同的字符,字符出现次数>
Map<Character,Integer> window = new HashMap<>();
char[] tt = t.toCharArray();
for (int i = 0; i < tt.length; i++) {
needs.put(tt[i],needs.getOrDefault(tt[i], 0 )+ 1);
}
int left = 0;
int right = 0;
int count = 0;
int ansLeft = 0;
int ansRight = 0;
int minLen = Integer.MAX_VALUE;
while(right < s.length()){
char ss = s.charAt(right);
if(needs.containsKey(ss)){
window.put(ss,window.getOrDefault(ss,0)+1);
if(window.get(ss).compareTo(needs.get(ss)) == 0){
//count代表符合要求的字符个数
count++;
}
}
right++;
while(count == needs.size()){
int tempLen = right - left + 1;
if(tempLen < minLen){
ansLeft = left;
ansRight = right;
minLen = tempLen;
}
//优化解,即left指针向右移动,缩小窗口
if(needs.containsKey(tt[left])){
window.put(tt[left],window.get(tt[left]) - 1);
if(window.get(tt[left]).compareTo(needs.get(tt[left])) < 0){
count--;
}
}
left++;
}
}
if(minLen == Integer.MAX_VALUE){
return "";
}
return s.substring(ansLeft,ansRight + 1);
}
public static void main(String[] args) {
String s = "ADOBECODEBANC";
String t = "ABC";
System.out.println(minWindow(s, t));
}
}