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
| public class Solution { public String minWindow(String S, String T) { int begin = 0, end = 0, minBegin = 0, minSize = S.length(), count = 0; HashMap<Character, Integer> stdMap = new HashMap<Character, Integer>(); HashMap<Character, Integer> map = new HashMap<Character, Integer>(); for (int i = 0; i < T.length(); i++) { char ch = T.charAt(i); if (stdMap.containsKey(ch)) { stdMap.put(ch, stdMap.get(ch) + 1); } else { stdMap.put(ch, 1); } map.put(ch, 0); } for (end = 0; end < S.length(); end++) { char ch = S.charAt(end); if (!stdMap.containsKey(ch)) { continue; } if (map.get(ch) < stdMap.get(ch)) { count++; } map.put(ch, map.get(ch) + 1); if (count == T.length()) { while (true) { char c = S.charAt(begin); if (stdMap.containsKey(c)) { if (map.get(c) > stdMap.get(c)) { map.put(c, map.get(c) - 1); } else { break; } } begin++; } if (end - begin + 1 < minSize) { minSize = end - begin + 1; minBegin = begin; } } } return count == T.length() ? S.substring(minBegin, minBegin + minSize) : ""; } }
|