Map<Character,Integer> ori = new HashMap<>(); Map<Character,Integer> cnt = new HashMap<>(); //这里用了两个哈希表 public String minWindow(String s, String t) { int tLen = t.length(); char[] c = t.toCharArray(); for(int i = 0;i<tLen;i++){ //将t中的元素全部放入哈希表中 ori.put(c[i],ori.getOrDefault(c[i],0)+1); //这里是值得注意学习,自己不会灵活运用的地方 } int l = 0,r = -1; int len = Integer.MAX_VALUE,ansL = -1,ansR = -1; int sLen = s.length(); while (r<sLen){ r++; if(r<sLen && ori.containsKey(s.charAt(r))){ //如果s[r]是有效字符,加入哈希表cnt中 cnt.put(s.charAt(r),cnt.getOrDefault(s.charAt(r),0)+1); } while (check() && l<=r){ if(r - l + 1<len){ len = r-l+1; ansL = l; ansR = r+1; } if(ori.containsKey(s.charAt(l))){ cnt.put(s.charAt(l),cnt.getOrDefault(s.charAt(l),0)-1); } l++; } } return ansL == -1?"":s.substring(ansL,ansR); } private boolean check() { for (Map.Entry<Character, Integer> characterIntegerEntry : ori.entrySet()) { Map.Entry entry = characterIntegerEntry; Character key = (Character) entry.getKey(); Integer val = (Integer) entry.getValue(); if (cnt.getOrDefault(key, 0) < val) { return false; } } return true; }