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