来个JAVA版本的,思路都一样
import java.util.*; public class Solution { /** * * @param S string字符串 * @param T string字符串 * @return string字符串 */ public String minWindow (String S, String T) { // write code here HashMap<Character,Integer> need = new HashMap<>(); HashMap<Character,Integer> window = new HashMap<>(); for(int i = 0;i < T.length();i++){ char c = T.charAt(i); need.put(c,need.getOrDefault(c,0) + 1); } int right = 0; int left = 0; int valid = 0; int minlen = Integer.MAX_VALUE; int start = 0; while(right < S.length()){ char c = S.charAt(right); right++; if(need.containsKey(c)){ window.put(c,window.getOrDefault(c,0) + 1); if(need.get(c) == window.get(c)){ valid++; } } while(valid == need.size()){ if(right - left < minlen){ start = left; minlen = right - left; } char d = S.charAt(left); left++; if(need.containsKey(d)){ if(need.get(d) == window.get(d)){ valid--; } window.put(d,window.getOrDefault(d,0) - 1); } } } return minlen == Integer.MAX_VALUE ? "" : S.substring(start,start + minlen); } }