Loading

12.25

76. 最小覆盖子串

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

注意:如果 s 中存在这样的子串,我们保证它是唯一的答案。

示例 1:

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

示例 2:

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

提示:

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

解答:这道题其实和leetcode第三道题目的做法类似的,做法都是双指针算法

  1. 使用两个哈希表分别记录字符串,s,t 中每个 字符出现的次数

  2. 定义变量cnt, 如果s 中字符出现的次数小于t ,则cnt加加,如果大于,则第二个指针开始移动

  3. 取最小

class Solution {
public:
    string minWindow(string s, string t) {
        string res;
        int cnt = 0;
        unordered_map<char, int>hs, ht;
        for(auto& c : t)ht[c]++;
        for(int i = 0, j = 0; i < s.size(); i++){
            hs[s[i]]++;
            if(hs[s[i]] <= ht[s[i]])cnt++;
            while(hs[s[j]] > ht[s[j]])hs[s[j++]]--;
            if(cnt == t.size()){
                if(res.empty() || i - j + 1 < res.size()){
                    res = s.substr(j, i - j + 1);
                }
            }
        }
        return res;
    }
};
posted @ 2020-12-25 23:26  桥木  阅读(114)  评论(0)    收藏  举报