手撕代码锻炼 3. 无重复字符的最长子串
作者:
liweidong
,
2023-03-19 17:01:59
,
所有人可见
,
阅读 38
/*
* 双指针
* 遍历所有字符串i,头
* 尾:j
* 用map存储其中的元素
* 检查i对应的元素是否存在,如果存在,j++,并删除该元素
*/
#include <iostream>
#include <unordered_set>
using namespace std;
int longestSubStr(string s){
// 最大长度
int res = -1;
// 存储j-i之间的元素
unordered_set<char> st;
// 尾指针
int j = 0;
// 头指针
for(int i=0;i<s.size();i++){
char c = s[i];
// j不断前进,并删除跳过的字符,知道st不含i对应的字符
while(j<i && st.count(c)){
st.erase(s[j]);
j ++;
}
st.insert(c);
res = max(res, i+1-j);
}
return res;
}
int main(){
string s = "pwwkew";
int max_len = longestSubStr(s);
cout<<max_len<<endl;
return 0;
}