首页 > 代码库 > LeetCode 76: Minimum Window Substring

LeetCode 76: Minimum Window Substring

 1 public class Solution {
 2     public String minWindow(String s, String t) {
 3         if (s.length() == 0 || s.length() < t.length() || t.length() == 0) {
 4             return "";
 5         }
 6         Map<Character, Integer> charMap = new HashMap<>();
 7         for (char c : t.toCharArray()) {
 8             charMap.put(c, charMap.getOrDefault(c, 0) + 1);
 9         }
10         int totalCount = 0;
11         int length = Integer.MAX_VALUE;
12         int startPoint = 0;
13         
14         
15         for (int left = 0, right = 0; right < s.length(); right++) {
16             if (charMap.containsKey(s.charAt(right))) {
17                 charMap.put(s.charAt(right), charMap.get(s.charAt(right)) - 1);
18                 if (charMap.get(s.charAt(right)) == 0) {
19                     totalCount++;
20                 }
21             }   
22             
23             while (totalCount == charMap.size()) {
24                 if (length > right - left + 1) {
25                     length = right - left + 1;
26                     startPoint = left;
27                 }
28                 
29                 if (charMap.containsKey(s.charAt(left))) {
30                     charMap.put(s.charAt(left), charMap.get(s.charAt(left)) + 1);
31                     if (charMap.get(s.charAt(left)) > 0) {
32                         totalCount--;
33                     }
34                 }
35                 left++;
36             }
37         }
38         return length == Integer.MAX_VALUE ? "" : s.substring(startPoint, startPoint + length);
39     }
40 }

 

LeetCode 76: Minimum Window Substring