LeetCode 76: Minimum Window Substring

Posted keepshuatishuati

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode76.Minimum Window Substring

LeetCode in Python 76. Minimum Window Substring

leetcode 76. Minimum Window Substring

Leetcode 76: Minimum Window Substring

leetcode 76-Minimum Window Substring(hard)

leetcode76 Minimum Window Substring