自从上班后就没怎么刷过题了,以后考虑更新点技术文章。
给你一个字符串 S、一个字符串 T,请在字符串 S 里面找出:包含 T 所有字母的最小子串。
示例:
输入: S = "ADOBECODEBANC", T = "ABC"
输出: "BANC"
说明:
如果 S 中不存这样的子串,则返回空字符串 ""。
如果 S 中存在这样的子串,我们保证它是唯一的答案。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-window-substring
题目也不算难,思路就是用滑动窗口, 代码也比较low
string minWindow(string s, string t) {
if (t == "") {
return "";
}
//每个字母出现的频率
int frequent[256];
memset(frequent, 0, sizeof(frequent));
//子串中有效的字母个数
int effect = 0;
//t串字母个数
int have = 0;
for (int i = 0; i < t.size(); ++i) {
++frequent[t[i]];
}
for (int i =0; i < 256; ++i) {
if (frequent[i])
have++;
}
int l = 0, r = 0;
int lr = -1, rr = -1;
while (r <= s.size()) {
if (effect != have || l >= r) {
//判断边界
if (r == s.size())
break;
--frequent[s[r]];
// cout << s[r] << " " << frequent[s[r]] << endl;
if (frequent[s[r]] == 0) {
effect++;
}
r++;
} else {
++frequent[s[l]];
//cout << s[l] << " " << frequent[s[l]] << endl;
if (frequent[s[l]] == 1) {
effect--;
}
l++;
}
//cout << l << " " << r <<" " <<effect <<endl;
if (effect == have) {
if (rr - lr > r - l || lr == -1) {
rr = r;
lr = l;
}
}
// cout <<"lr rr" << lr << " " << rr << endl;
}
if (lr == -1) {
return "";
}
string res;
for (int i = lr; i < rr; ++i) {
res.push_back(s[i]);
}
return res;
}