76.最小覆盖子串

给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 "" 。

注意:

  • 对于 t 中重复字符,我们寻找的子字符串中该字符数量必须不少于 t 中该字符数量。
  • 如果 s 中存在这样的子串,我们保证它是唯一的答案。

示例 1:

输入:s = "ADOBECODEBANC", t = "ABC"
输出:"BANC"

示例 2:

输入:s = "a", t = "a"
输出:"a"

示例 3:

输入: s = "a", t = "aa"
输出: ""
解释: t 中两个字符 'a' 均应包含在 s 的子串中,
因此没有符合条件的子字符串,返回空字符串。

提示:

  • 1 <= s.length, t.length <= 105
  • s 和 t 由英文字母组成

进阶:你能设计一个在 o(n) 时间内解决此问题的算法吗?

方法:滑动窗口

 

 1 /**
 2  * @param {string} s
 3  * @param {string} t
 4  * @return {string}
 5  */
 6 var minWindow = function(s, t) {
 7  let l = 0
 8     let r = 0
 9     const need = new Map()
10     for(let c of t){
11         need.set( c,need.has(c) ? need.get(c) + 1 : 1)
12     }
13 
14     let needType = need.size
15     let res = ''
16     while(r<s.length){
17         let c = s[r]
18         if(need.has(c)){
19             need.set( c,need.get(c) -1 )
20             if( need.get(c) === 0) needType -= 1
21         }
22         
23         while(needType === 0){
24             const newRes = s.substring(l,r+1)
25             if( !res || newRes.length < res.length ) res = newRes
26 
27             const c2 = s[l]
28             if(need.has(c2)){
29                 need.set(c2,need.get(c2) + 1)
30                 if( need.get(c2) === 1 ) needType += 1
31             }
32             l += 1
33         }
34         r += 1
35     }
36 return res;
37 };

 

posted @ 2022-11-09 20:49  icyyyy  阅读(23)  评论(0)    收藏  举报