/*
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
*/
#include <string>
#include <iostream>
using namespace std;
int lengthOfLongestSubstring(string s) {
int length = 0;
int result = 0;
string temp = s;
string substring = "";
for (int i = 0; temp.length()+substring.length() >result && i<s.length();i++)
{
if (substring.find(s[i]) == -1)
{
substring += s[i];
temp = temp.substr(1, temp.length() - 1);
}
else
{
substring = substring.substr(substring.find(s[i]) + 1, substring.length() - substring.find(s[i]) - 1);
temp = s.substr(i + 1, s.length() - i - 1);
substring += s[i];
}
length = substring.length();
if (length > result)
result = length;
}
return result;
}
int main()
{
string s;
cin >> s;
cout << lengthOfLongestSubstring(s) << endl;
return 0;
}
给定一个子串,寻找没有重复字符的最长子串
最新推荐文章于 2025-02-08 09:15:49 发布
本文介绍了一种算法,用于找出给定字符串中最长的不包含重复字符的子串长度。通过逐步遍历并检查字符是否重复来实现,确保找到符合条件的最大子串。
2833

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



