最大不重复子串

#include <iostream>
#include <string>
#include <hash_map>

using namespace std;
using namespace stdext;

//acronym : LNS
pair<string, size_t> longest_norepeat_substring( string& str )
{
	hash_map<char, int> char_index;//save the character and last postion it appears

	size_t currentStart = 0;//start position of the LNS
	size_t repeated_postion = 0;//the last postion of the repeated character
	size_t maxLength = 0;//max length of the LNS
	size_t curLength = 0;//current LNS length
	size_t finalStart = 0;
	//O(N) traverse
	for( size_t i = 0 ; i < str.size() ; i++ )
	{
		if( char_index.find( str[i] ) != char_index.end() ) //repeated character
		{
			char repeatChar = str[i];
			//if the repeated position is behind the current start position
			//change the current start postion of LNS
			repeated_postion = char_index[repeatChar];
			if( repeated_postion + 1 > currentStart )
				currentStart = repeated_postion + 1;
			//also change the current LNS length
			curLength = i - currentStart + 1;

			//update the last appearance of the repeated character
			char_index[repeatChar] = i;            
		}
		else//not repeated character
		{
			char_index.insert( pair<char, int>( str[i], i ) );
			curLength++;
			//update the max LNS length
			if( curLength > maxLength )
			{
				maxLength = curLength;		
				finalStart = currentStart;//remember the start position of final result
			}
		}
	}
	return pair<string, size_t>( str.substr( finalStart, maxLength ), maxLength );
}

int main()
{
	string str = "aabcdebfabcd";
	cout<<longest_norepeat_substring( str ).first<<endl;
	cout<<longest_norepeat_substring( str ).second<<endl;

	string s = "aaaaaa";
	cout<<longest_norepeat_substring( s ).first<<endl;
	cout<<longest_norepeat_substring( s ).second<<endl;
}

 

posted @ 2013-04-28 22:05  xiaowenchao  阅读(194)  评论(0编辑  收藏  举报