(algorithm) the longest non-repeating substring

Source: Internet
Author: User

Topic:

Finds a contiguous substring from a string in which any two characters in the substring cannot be the same, finds the maximum length of the substring and outputs a longest, non-repeating substring.

Ideas:

Use hash table hashtable[256] to save the characters that have occurred, and then iterate through the string from the beginning,

1, if the current character Ch has already appeared (Hashtable[ch]==1), it indicates that a local longest non-repeating substring has occurred:

At this point the substring length is judged to be greater than Mlen, and if so, the Mlen is updated, and the starting position of the oldest string is Mstart.

At the same time the hash table between start and repeat character ch is reset to 0 (indicating that no occurrences have occurred), the corresponding length len is also reduced, and then the next character of CH as the beginning of the new substring;

2. If the current character Ch does not appear:

The Hashtable is set to 1 (indicating that it has occurred) and len++.

Complexity of Time:

O (N)

Code:
#include <iostream>using namespacestd;intGETLONGESTUNREPEATEDSUBSTR (Const string&str) {    inthashtable[ the]={0}; intstart=0; intmstart=0; intmlen=0; intidx=0; intlen=0;  while(idx!=str.size ()) {        if(hashtable[str[idx]]==1){            if(len>Mlen) {Mstart=start; Mlen=Len; }             while(str[start]!=Str[idx]) {Hashtable[str[start]]=0; Start++; Len--; } Start++; }        Else{Hashtable[str[idx]]=1; Len++; } idx++; }    if(len>Mlen) {Mlen=Len; Mstart=start; } cout<< str.substr (Mstart,mlen) <<Endl; returnMlen;}intMain () {stringstr;  while(cin>>str) {cout<< getlongestunrepeatedsubstr (str) <<Endl; }    return 0;}

(algorithm) the longest non-repeating substring

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.