Leetcode 76.最小覆盖子串

最小覆盖子串

给定一个字符串 S 和一个字符串 T,请在 S 中找出包含 T 所有字母的最小子串。

示例:

输入: S = "ADOBECODEBANC", T = "ABC"

输出: "BANC"

说明:

  • 如果 S 中不存这样的子串,则返回空字符串 ""。
  • 如果 S 中存在这样的子串,我们保证它是唯一的答案。

思路:采用滑动窗口,窗口有左右边界,先通过扩展右边界找出一个包含T中所有字符的子串,然后收缩左边界,直到不能再收缩。记录此时的子串。然后收缩左边界,继续扩展右边界,直到再找到满足要求的子串,和上次的进行比较,保存更小的子串。返回执行,直到右边界到达S串尾,且左边界不能再收缩。

 1 import java.util.*;
 2 
 3 public class Solution {
 4     public static String minWindow(String s,String t){
 5         Map<Character,Integer> map=new HashMap<>();
 6         int min=Integer.MAX_VALUE;
 7         int minStart=0,minEnd=0;
 8         int count=t.length();
 9         for(char c:t.toCharArray()){
10             map.put(c,map.containsKey(c)?map.get(c)+1:1);
11         }
12         int left=0;
13         for(int right=0;right<s.length();right++){
14             char val=s.charAt(right);
15             if(map.containsKey(val)){
16                 map.put(val,map.get(val)-1);
17                 if(map.get(val)>=0){
18                     count--;
19                 }
20             }
21             while(count==0){
22                 if(right-left<min){
23                     min=right-left;
24                     minStart=left;
25                     minEnd=right;
26                 }
27                 char temp=s.charAt(left);
28                 if(map.containsKey(temp)){
29                     map.put(temp,map.get(temp)+1);
30                     if(map.get(temp)>0) count++;
31                 }
32                 left++;
33             }
34         }
35         return min==Integer.MAX_VALUE?"":s.substring(minStart,minEnd+1);
36     }
37 }

猜你喜欢

转载自www.cnblogs.com/kexinxin/p/10163053.html