1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| class Solution { public String minWindow(String s, String t) { if(s.length() == 0 || t.length() == 0) { return ""; } Map<Character, Integer> mapT = new HashMap<>(); Map<Character, Integer> mapW = new HashMap<>(); for(int i = 0; i < t.length(); i ++) { char ch = t.charAt(i); mapT.put(ch, mapT.getOrDefault(ch, 0) + 1); } int tCount = mapT.size(); int resStart = 0, resLen = Integer.MAX_VALUE; int left = 0, right = 0; while(right < s.length()) { char rightChar = s.charAt(right); mapW.put(rightChar, mapW.getOrDefault(rightChar, 0) + 1);
while(isFullInclude(mapT, mapW)) { int windowLen = right - left + 1; if(windowLen < resLen) { resLen = windowLen; resStart = left; }
char leftChar = s.charAt(left); mapW.put(leftChar, mapW.get(leftChar) - 1); left ++; } right ++; } if(resLen == Integer.MAX_VALUE) return ""; return s.substring(resStart, resStart + resLen); }
private static boolean isFullInclude(Map<Character, Integer> mapT, Map<Character, Integer> mapW) { for(Map.Entry<Character, Integer> key : mapT.entrySet()) { char c = key.getKey(); int valueT = key.getValue(); if(mapW.containsKey(c)) { int valueW = mapW.get(c); if(valueT > valueW) { return false; } } else { return false; } } return true; } }
|