剑指 Offer II 017. 含有所有字符的最短字符串

给定两个字符串 s 和 t 。返回 s 中包含 t 的所有字符的最短子字符串。如果 s 中不存在符合条件的子字符串,则返回空字符串 "" 。

如果 s 中存在多个符合条件的子字符串,返回任意一个。

注意: 对于 t 中重复字符,我们寻找的子字符串中该字符数量必须不少于 t 中该字符数量。

示例 1:

输入:s = "ADOBECODEBANC", t = "ABC"
输出:"BANC"
解释:最短子字符串 "BANC" 包含了字符串 t 的所有字符 'A'、'B'、'C'
示例 2:

输入:s = "a", t = "a"
输出:"a"
示例 3:

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

提示:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/M1oyTv
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 1 class Solution {
 2 public:
 3     string minWindow(string s, string t) {
 4         unordered_map<char,int>ms,mt;
 5        if(t.size()>s.size()) return "";
 6        for(auto &i:t ) mt[i]++;//遍历子串
 7        int l=0,r=0,cnt=0;
 8        string ans;
 9        for(;l<s.size();l++)//遍历母串,才用滑动串口方法,L和R被我搞反了,不影响逻辑
10        {
11            ms[s[l]]++;   
12            if(ms[s[l]]<=mt[s[l]]) cnt++;
13            while(ms[s[r]]>mt[s[r]])  //左边界右移的原因:1,当前字母不在子串中,2.当前字母在r-l之前有重复,可以跳跃。
14            {
15                ms[s[r]]--;r++;
16            }
17            if(cnt==t.size())//维护一个最短的串
18            {
19               if(ans.empty()||ans.size()>l-r+1)
20                ans=s.substr(r,l-r+1);
21            }
22 
23        }
24        return ans;
25 
26     }
27 };
原文地址:https://www.cnblogs.com/sylvia1111/p/15801332.html