滑动窗口:最长不含重复字符的子字符串
从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度,如string s = "abcdacbefbed";
最长子字符串的长度为6:dacbef
#include <iostream>
#include <unordered_set>
using namespace std;
int func(string s) {
unordered_set<char> occ;
int n = s.size();
int rk = -1, ans = 0;
for (int i = 0; i < n; ++i)
{
if (i != 0)
{
occ.erase(s[i - 1]);
}
while (rk + 1 < n && !occ.count(s[rk + 1]))
{
occ.insert(s[rk + 1]);
++rk;
}
ans = max(ans, rk - i + 1);//可以加判断记录最长长度和对应的起始地址
}
return ans;
}
int main()
{
string s = "abcdacbefbed";
cout << func(s) << endl;
return 0;
}