题目描述:
给你一个字符串
s
、一个字符串t
。返回s
中涵盖t
所有字符的最小子串(子串指排放连续的子序列)。如果s
中不存在涵盖t
所有字符的子串,则返回空字符串""
。
输入:s = "ADOBECODEBANC", t = "ABC" 输出:"BANC" 解释:最小覆盖子串 "BANC" 包含来自字符串 t 的 'A'、'B' 和 'C'。
/*最小覆盖子串*/
#include <string>
#include <unordered_map>
#include <limits>
#include <vector>
std::string minimal_hash_covering_substring(std::string const & s, std::string const & p){
int s_length { static_cast<int>(s.length()) };
int p_length { static_cast<int>(p.length()) };
if(s_length < p_length) return std::string {};
std::vector<std::pair<int, char>> shrinks {};
shrinks.reserve(s_length << 1 | 1);
std::unordered_map<char, int> needed {};
for(auto const & c : p) (void) needed[c] ++;
int different { static_cast<int>(needed.size()) };
for(int i {}; i < s_length; ++i) if(needed.count(s[i])) shrinks.emplace_back(i, s[i]);
std::unordered_map<char, int> hash {};
int first {};
int last {};
int start {};
int validates {};
int result { std::numeric_limits<int>::max() };
while(! (last == s_length)){
auto last_char { shrinks[last ++].first };
++ hash[last_char];
if(hash.count(last_char) == needed.count(last_char)) ++ validates;
while(validates == different){
auto current_length { shrinks[last - 1].second - shrinks[first].second + 1 };
if(current_length < result){
result = current_length;
start = shrinks[first].second;
}
auto first_char { shrinks[first ++].first };
if(hash.count(first_char) == needed.count(first_char)) -- validates;
-- hash[first_char];
}
}
return result == std::numeric_limits<int>::max() ? std::string {} : s.substr(start, result);
}