Efficient Implementation of longest non-repeated substrings

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.