1. Center Expansion
The Central extension is to take each letter of a given string as a center , extending to both sides, to find the longest child palindrome string. The algorithm complexity is O (n^2).
But there are two things to consider:
1, like ABA, so the length is odd.
2, want to ABBA, so the length is even. The code is as follows:
stringFindlongestpalindrome (string&s) { Const intLength=s.size (); intMaxlength=0; intstart; for(intI=0; i<length;i++)//an odd length { intj=i-1, k=i+1; while(j>=0&&k<length&&s.at (j) = =s.at (k)) { if(k-j+1>maxlength) {MaxLength=k-j+1; Start=J; } J--; K++; } } for(intI=0; i<length;i++)//length is even { intj=i,k=i+1; while(j>=0&&k<length&&s.at (j) = =s.at (k)) { if(k-j+1>maxlength) {MaxLength=k-j+1; Start=J; } J--; K++; } } if(maxlength>0) returns.substr (start,maxlength); returnNULL;}
2. Dynamic PlanningThere is a mother string s, which we use to
c[i, j] = 1
denote substring s[i. J] for Palindrome substrings, space and algorithmic complexity are also O (n^2). Then there is the recursive type:
c[i,j]={c[i+1, j−1], if s[i]=s[j] 0 , if S[i]≠s[j]
Recursion means that in the s[i] = s[j]
case, if S[I+1..J-1] is a palindrome substring, then s[i. J] is also a palindrome substring, if s[i+1..j-1] is not a palindrome string, then S[i. J] Nor is it a palindrome string.
Initial state:
1 c[i][i+11if s[i] = = s[i+1]
The above expression represents a single character, two characters are palindrome string[J]
intLongestpald (Char*str) { intLen =strlen (str); intC[maxlen][maxlen]; inti,j; intLongest =1; ASSERT (str!=NULL); if(len = =1) { return 1; } //initialization for(i =0; i < Len; i++) {C[i][i]=1; if(Str[i] = = str[i+1]) C[i][i+1] =1; } for(i =0; i < Len; i++) { for(j = i+2; J <= Len; J + +) { if(Str[i] = =Str[j]) {C[i][j]= c[i+1][j-1]; //find longest palindrome substring if(C[i][j]) {intn = j-i +1; if(Longest <N) Longest=N; } } Else{C[i][j]=0; } } } returnlongest;}
3. Violence Law
The most easy to think of is the violent crack, find out each string, then judge is not a palindrome, found the longest one.
Ask each substring time complexity O (n^2), determine whether the substring is a palindrome O (N), the two are multiplied, so the time complexity is O (n^3).
stringFindlongestpalindrome (string&s) { intLength=s.size ();//string Length intMaxlength=0;//Longest palindrome string length intStart//Longest palindrome string start address
for(intI=0; i<length;i++)//Start Address for(intj=i+1; j<length;j++)//End Address { intTMP1,TMP2; for(tmp1=i,tmp2=j;tmp1<tmp2;tmp1++,tmp2--)//Judging is not a palindrome { if(s.at (TMP1)! =s.at (TMP2)) Break; } if(tmp1>=tmp2&&j-i>maxlength) {MaxLength=j-i+1; Start=i; } } if(maxlength>0) returnS.substr (start,maxlength);//To find a child string returnNULL;}
4.Manacher Law (to be continued)
Algorithm and longest palindrome strings