3. 无重复字符的最长子串
最典型的滑动窗口题目
right要找到新字符,才加1,扩大窗口
left要发现旧字符就加1,缩小窗口,直到right处的flag[s[right]]值变为0,right才继续增加
需要注意的就是right++;的位置,需要考虑清楚
#define MAX(x,y) (x)>(y)?(x):(y)
int lengthOfLongestSubstring(char * s){
int left=0,right=0;
int len=strlen(s);
int maxlen=0;
int flag[256]={0};
while(right<len){
int idx=s[right];
if(flag[idx]==0){
flag[idx]++;
maxlen=MAX(maxlen,right-left+1);
right++;//right++的位置,开始放在所有操作结束后,是不对的,在"bbbbb"用例中会出错。
}else{
flag[s[left]]--;
left++;
}
// right++; //right++的位置,开始放在这里,是不对的,在"bbbbb"用例中会出错。
}
return maxlen;
}
76. 最小覆盖子串
char * minWindow(char * s, char * t){
int need[300] = { 0 };
int window[300] = { 0 };
int needlen = 0,minlen=INT_MAX;
char* res = malloc(100000);
memset(res, '\0', 100000);
for (int i = 0; i < strlen(t); i++) {
char idx = t[i];
if (need[idx] == 0)
needlen++;
need[idx]++;
}
int match = 0;
int right = 0, left = 0, start = 0;
while (right < strlen(s)) {
char c1 = s[right];
if (need[c1]) {
window[c1]++;
if (window[c1] == need[c1]) {
match++;
}
}
right++;
while (match == needlen) {
if (right - left < minlen) {
start = left;
minlen = right - left;
}
char c2 = s[left];
if (need[c2]) {
window[c2]--;
if (window[c2] < need[c2]) {
match--;
}
}
left++;
}
}
if (minlen == INT_MAX)res = "";
else {
res = memcpy(res, s + start, minlen);
}
return res;
}
438. 找到字符串中所有字母异位词
与上一题76. 最小覆盖子串 的区别在下面这两句,因为要找长度完全符合只是顺序不同的字符串。
while (match == needlen) {
if (right - left == strlen(p)) {
res[k++]=left;
}
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* findAnagrams(char * s, char * p, int* returnSize){
int need[200] = { 0 };
int window[200] = { 0 };
int needlen = 0, minlen = INT_MAX;
int* res = malloc(1000000);
for (int i = 0; i < strlen(p); i++) {
char idx = p[i];
if (need[idx] == 0)
needlen++;
need[idx]++;
}
int match = 0,k=0;
int right = 0, left = 0;
while (right < strlen(s)) {
char c1 = s[right];
if (need[c1]) {
window[c1]++;
if (window[c1] == need[c1]) {
match++;
}
}
right++;
while (match == needlen) {
if (right - left == strlen(p)) {
res[k++]=left;
}
char c2 = s[left];
if (need[c2]) {
window[c2]--;
if (window[c2] < need[c2]) {
match--;
}
}
left++;
}
}
*returnSize = k;
return res;
}
最后总结
通过上面三道题,我们可以总结出滑动窗口算法的抽象思想:
int left = 0, right = 0;
while (right < s.size()) {
window.add(s[right]);
right++;
while (valid) {
window.remove(s[left]);
left++;
}
}