For the substring of a string, we often need to use the accessed information to reduce complexity and improve efficiency, manacher's algorithm provides a good mechanism, although it is not easy to understand in some places
First, let's talk about the core idea: first pre-process the original string and convert the string "ABC" to the form of "$ # A # B # C, this not only avoids access out of bounds, but also ensures that each character has at least one symmetric string (real character or false "#").
Reserve two pairs of variables (the current central location "center", the farthest location "R" on the right side of the string, and the symmetric left side "L") (the current access character location "I ", and the symmetric position "I _" relative to the current access location "center _")
#include <string.h>#include <stdio.h>#include <iostream>using namespace std;void preprocess(char str[],char result[]);int min(int a, int b);int p[2020];int main(){ int center,i,i_,L,R,j; char str[1010],result[2020]; int maxlen, index,len; cin.getline(str,1000,‘\n‘); preprocess(str,result); /*printf("%s",result);*/ //handle the string center=0,R=0; p[0]=0; len = strlen(result); //i from 1,so the begging position is placed ‘$‘ to avoid the segment error for(i=1;i<len-1;i++){ i_=center*2-i;//the symmetric position L=center*2-R; p[i] = (R > i) ? min(R - i, p[i_]) : 0; while (i + p[i] + 1<len&&result[i + p[i] + 1] == result[ i- p[i] - 1]) p[i]++; //if R expands,then modify it if (R - i <p[i]){ center = i; R = i + p[i]; } } //find the maximum length in p maxlen = 0, index = 0; for (i = 0; i < strlen(result); i++){ if (maxlen < p[i]){ maxlen = p[i]; index = i; } } printf("%d", maxlen); return 0;}void preprocess(char str[],char result[]){ int len=strlen(str),i,j; result[0]=‘$‘;//indicates the start for(i=0,j=1;i<len;i++){ result[j++]=‘#‘; result[j++]=str[i]; } result[j]=‘#‘; result[j+1]=‘\0‘;}int min(int a, int b){ if (a < b) return a; else return b;}
P [I] records the right symmetric length of the character at position I (including STR [I] itself). The most important thing is to understand the following sentence:
p[i] = (R > i) ? min(R - i, p[i_]) : 0; while (i + p[i] + 1<len&&result[i + p[i] + 1] == result[ i- p[i] - 1]) p[i]++; //if R expands,then modify it if (R - i <p[i]){ center = i; R = i + p[i]; }
Longest retrieval string understanding (learn manacher's algorithm)