Leetcode-76.最小覆盖子串
给定一个字符串 S 和一个字符串 T,请在 S 中找出包含 T 所有字母的最小子串。
示例:
输入: S = “ADOBECODEBANC”, T = “ABC”
输出: “BANC”
说明:
如果 S 中不存这样的子串,则返回空字符串 “”。
如果 S 中存在这样的子串,我们保证它是唯一的答案。
思路:
初试两个指针,一个为begin,一个为end,end依次遍历串S,begin用来缩小与end 的距离,判断begin中字符多余或者在T中没有出现过,则begin++,并且用res记录出现过的子串,依次这样遍历。

代码:
class Solution {
public:
bool is_all(int temp_num[], int t_num[], string &t){
for(int i = 0; i < t.size(); i++){
if(temp_num[t[i]] < t_num[t[i]]){
return false;
}
}
return true;
}
string minWindow(string s, string t) {
int begin = 0;
string res;
int t_num[128] = {0};
int temp_num[128] = {0};
for(int i = 0; i < t.size(); i++){
t_num[t[i]]++;
}
for(int i = 0; i < s.size(); i++){
temp_num[s[i]]++;
while(begin < i){
char begin_char = s[begin];
if(t_num[begin_char] ==0){
begin++;
}else if(temp_num[begin_char] > t_num[begin_char]){
temp_num[begin_char]--;
begin++;
}else{
break;
}
}
if((i - begin + 1 < res.size() || res.empty()) && is_all(temp_num, t_num, t)){
res = s.substr(begin, i - begin + 1);
}
}
return res;
}
};
Leetcode-76最小覆盖子串解题思路
博客围绕Leetcode-76最小覆盖子串问题展开,给定字符串S和T,需在S中找出包含T所有字母的最小子串。给出示例及说明,还阐述了解题思路,即使用两个指针begin和end,end遍历S,begin缩小与end距离,同时用res记录子串。
867

被折叠的 条评论
为什么被折叠?



