首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。