I found the code written by searching for man-hours exercises N years ago and thought it was okay to look for the first non-repeated substring in the English string. Only one traversal is required, but only applicable to English.
Char * GetMaxSubStr (char * str)
{
Int hash [256]; // the position where each character appears in the hash record
Int I = 0;
For (; I <256; I ++) // Initialization
{
Hash [I] =-1;
} Www.2cto.com
Int CurrentStart = 0, CurrentLength = 0, MaxStart = 0, MaxEnd = 0;
Int strLen = strlen (str );
For (I = 0; I <strLen; I ++)
{
If (CurrentStart> hash [str [I]) // if there are no duplicates
{
Hash [str [I] = I;
}
Else
{
CurrentLength = I-CurrentStart; // current length
If (CurrentLength> MaxEnd-MaxStart) // if the current length is the longest
{
MaxEnd = I;
MaxStart = CurrentStart;
}
CurrentStart = hash [str [I] + 1; // update the current longest start point
Hash [str [I] = I; // position of the updated character
}
}
If (MaxEnd = 0) // No repeated characters, return the source string
{
Char * reStr = new char [strLen + 1];
Strcpy (reStr, str );
Return reStr;
}
Int MaxLength = MaxEnd-MaxStart;
Char * reStr = new char [MaxLength + 1];
Memset (reStr, 0, MaxLength + 1 );
Strncpy (reStr, str + MaxStart, MaxLength );
Return reStr;
}
From: ifeng Column