给你一个字符串 s
、一个字符串 t
。返回 s
中涵盖 t
所有字符的最小子串。如果 s
中不存在涵盖 t
所有字符的子串,则返回空字符串 ""
。
package com.jtc.fortest;
import java.util.HashMap;
public class leetcode76 {
public static void main(String[] args) {
String s = "ADOBECODEBANC";
String t = "ABC";
String s1 = minWindow(s, t);
System.out.println(s1);
}
public static String minWindow(String s, String t) {
HashMap<Character,Integer> need = new HashMap<>();
HashMap<Character,Integer> window = new HashMap<>();
for(char ch : t.toCharArray()){
need.put(ch,need.getOrDefault(ch,0)+1);
}
int left = 0;
int right = 0;
int vaild = 0;
int start = 0;
int len = Integer.MAX_VALUE;
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))){
vaild++;
}
}
while(vaild == need.size()){
//只有比len更小时才更新
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))){
vaild--;
}
window.put(d,window.getOrDefault(d,0)-1);
}
}
}
return len == Integer.MAX_VALUE ? "" : s.substring(start,start+len);
}
}
执行用时:10 ms, 在所有 Java 提交中击败了65.58%的用户
内存消耗:41.9 MB, 在所有 Java 提交中击败了47.81%的用户
通过测试用例:266 / 266