https://leetcode.cn/problems/longest-substring-without-repeating-characters/
#include<iostream>
#include<string>
#include<unordered_set>
using namespace std;
int longest_norepeated_character_substr(string str){
int maxlen(1);
unordered_set<char> sets;
sets.insert(str[0]);
for(size_t istart(0),iend(0);istart<str.size()-1;istart++){
while(iend+1<str.size() && sets.count(str[iend+1])<=0)
sets.insert(str[++iend]);
if(iend-istart+1>maxlen)
maxlen=iend-istart+1;
sets.erase(str[istart]);
}
return maxlen;
}
int main(int argc,char *argv[]){
cout<<longest_norepeated_character_substr((string)"abcabcbb")<<endl;
cout<<longest_norepeated_character_substr((string)"bbbbb")<<endl;
cout<<longest_norepeated_character_substr((string)"pwwkew")<<endl;
}
该代码实现了一个C++函数,用于解决LeetCode中的经典问题——找到给定字符串中不包含重复字符的最长子串的长度。方法是使用滑动窗口和哈希集合来跟踪已出现的字符,从而高效地找出最长子串。
422

被折叠的 条评论
为什么被折叠?



