【LeetCode】#76最小覆盖子串(Minimum Window Substring)
题目描述
给定一个字符串 S 和一个字符串 T,请在 S 中找出包含 T 所有字母的最小子串。
示例
输入: S = “ADOBECODEBANC”, T = “ABC”
输出: “BANC”
Description
Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
Example
Input: S = “ADOBECODEBANC”, T = “ABC”
Output: “BANC”
解法
class Solution {
public String minWindow(String s, String t) {
Map<Character, Integer> map = new HashMap<>();
int min = Integer.MAX_VALUE;
int minStart = 0, minEnd = 0;
int count = t.length();
for(char c : t.toCharArray()){
map.put(c, map.containsKey(c) ? map.get(c)+1 : 1);
}
int left = 0;
for(int right=0; right<s.length(); right++){
char val = s.charAt(right);
if(map.containsKey(val)){
map.put(val, map.get(val)-1);
if(map.get(val)>=0){
count--;
}
}
while(count==0){
if(right-left<min){
min = right-left;
minStart = left;
minEnd = right;
}
char temp = s.charAt(left);
if(map.containsKey(temp)){
map.put(temp, map.get(temp)+1);
if(map.get(temp)>0) count++;
}
left++;
}
}
return min == Integer.MAX_VALUE ? "" : s.substring(minStart, minEnd+1);
}
}