Leetcode-最小覆盖子串
题目描述
给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 "" 。
注意:如果 s 中存在这样的子串,我们保证它是唯一的答案。
示例 1:
输入:s = "ADOBECODEBANC", t = "ABC"
输出:"BANC"
示例 2:
输入:s = "a", t = "a"
输出:"a"
思路:哈希表+滑动窗口
#include <iostream>
#include <vector>
#include <map>
#include <climits>
using namespace std;
class Solution {
public:
string minWindow(string s, string t) {
map<char, int> t_map;
map<char, int> s_map;
for(auto item:t)
t_map[item]++;
int left = 0;
int right = 0;
int target_left_loc = -1;
int target_right_loc = 0;
int mininim_valid_length = INT_MAX;
int matched = 0;
while (left<=right && right<s.length()){
char s_c = s[right];
s_map[s_c]++;
if(t_map.count(s_c)!=0 && s_map[s_c]==t_map[s_c])
matched += t_map[s_c];
while(left<=right && matched == t.length()){
int curr_valid_length = right - left + 1;
if(curr_valid_length < mininim_valid_length){
mininim_valid_length = curr_valid_length;
target_left_loc = left;
target_right_loc = right;
}
s_c = s[left];
if(t_map.count(s_c)!=0){
s_map[s_c]--;
if(s_map[s_c] < t_map[s_c])
matched -= t_map[s_c];
}
left++;
}
right++;
}
if(target_left_loc <= target_right_loc && target_left_loc!=-1){
string res = "";
for(int i=target_left_loc; i<=target_right_loc; i++)
res += s[i];
return res;
}else
return "";
}
};
int main(int argc, char const *argv[]){
string test_s = "a";
string test_t = "a";
Solution solu;
cout<<solu.minWindow(test_s, test_t)<<endl;
return 0;
}