1. 程式人生 > >給定一個子串,尋找沒有重複字元的最長子串

給定一個子串,尋找沒有重複字元的最長子串

/*
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;
}