一、滑动窗口基本框架
while (r < s.size()) {
win.add(s[r]);//增大窗口
r++;
//窗口数据更新
while (r - l > x.size()) {//通常借助此收缩窗口
win.remove(s[l]);
l++;
//窗口数据更新
}
}
算法技巧的时间复杂度是 O(N)。
二、相关题目
1、最小覆盖子串
题目:在 S(source) 中找到包含 T(target) 中全部字母的一个子串,且这个子串一定是所有可能子串中最短的。
思路:
(1)在字符串S中使用双指针的左右技巧,初始化 l=r=0,把索引左闭右开区间[l,r)称作一个窗口。
(2)增大r扩大窗口,直到窗口中的字符满足要求。
(3)停止增大r,增大l,缩小窗口,直到窗口中的字符串不符合要求,每一步都更新结果。
(4)重复(2)(3)直到r走到尽头。
完整代码如下:
string slidWin(string s, string t) {
unordered_map<char, int>need, win;
for (auto& c : t)need[c]++;
int l = 0, r = 0;
int val = 0;
int start = 0, len = INT_MAX;//记录最小子串的索引以及长度
while (r < s.size()) {
char c = s[r];
r++;
//窗口数据更新
if (need.count(c)) {
win[c]++;
if (win[c] == need[c])val++;
}
while (val == need.size()) {
//更新最小覆盖子串
if (r - l < len) {
start = l;
len = r - l;
}
char d = s[l];
l++;
//窗口数据更新
if (need.count(d)) {
if (need[d] == win[d])val--;
win[d]--;
}
}
}
return len == INT_MAX ? "" : s.substr(start, len);
}
其中val标识窗口中满足need条件的字符的个数,如果valneed.size()表明窗口条件满足,即得到了可行的覆盖子串,可以收缩窗口。
2、字符串排列
给定两个字符串s1和s2,判断s2是否包含s1的排列。换句话说,第一个字符串的排列之一是第二个字符串的子串。
(1)L缩小窗口的时机是窗口大小大于t.size()时。
(2)当valneed.size()时,说明窗口排列合法,返回true.
//判断s中是否存在t的排列
bool checkInclusion(string t, string s) {
unordered_map<char, int>need, win;
for (auto& c : t)need[c]++;
int l = 0, r = 0;
int val = 0;
while (r < s.size()) {
char c = s[r];
r++;
//窗口数据更新
if (need.count(c)) {
win[c]++;
if (win[c] == need[c])val++;
}
while (r - l >= t.size()) {
if (val == need.size())return true;
char d = s[l];
l++;
//窗口数据更新
if (need.count(d)) {
if (win[d] == need[d])val--;
win[d]--;
}
}
}
return false;
}
3、找所有字母的异位词
给定字符串s和p,找s中所有是p的字母异位词的子串,返回子串的起始索引。
字母异位词指字母相同,但是排列不同的字符串。
//找所有字母的异位词
vector<int>findYiwei(string s, string t) {
unordered_map<char, int>need, win;
for (auto& c : t)need[c]++;
int l = 0, r = 0;
int val = 0;
vector<int>ans;
while (r < s.size()) {
char c = s[r];
r++;
//窗口数据更新
if (need.count(c)) {
win[c]++;
if (win[c] == need[c])val++;
}
while (r - l >= t.size()) {
if (val == need.size()) {
ans.push_back(l);
}
char d = s[l];
//窗口数据更新
if (need.count(d)) {
if (win[d] == need[d])val--;
win[d]--;
}
}
}
return ans;
}
4、最长无重复子串
给定一个字符串,找出其中不含有重复字符的最长子串的长度
//最长无重复子串
int maxLength(string s) {
unordered_map<char, int>win;
int l = 0, r = 0;
int res = 0;
while (r < s.size()) {
char c = s[r];
r++;
//窗口数据更新
win[c]++;
while (win[c] > 1) {
char d = s[l];
l++;
win[d]--;
}
res = max(res, r - l);
}
return res;
}