/*
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;
}
给定一个子串,寻找没有重复字符的最长子串
最新推荐文章于 2021-03-12 17:57:37 发布