A palindrome reads and reads backwards, with the same results, such as ABCBA or ABBA, the topic is to be in a string to the longest palindrome substring
First we can consider the general situation, first remove any substring from the string to determine whether it is a palindrome string, this method can be called the Brute force solution, so the time complexity can reach O (n3)
The code looks like this:
ImportJava.util.*; Public classpalindrome {//the function of judging palindrome Public BooleanIshuiwen (String A,intN) { intK = N/2; for(inti = 0; I < K; ++i) {if(A.charat (i)! = A.charat (n-1-i))return false; } return true; } Public intGetlongestpalindrome (String A,intN) {intMaxlen=0; for(intI=0;i< N; i++) { for(intj=i+1; j<=n; j + +) { //The two-layer loop iterates through all the substrings and determines whether it is a palindrome . if(Ishuiwen (A.substring (i, J), Ji)) {if(j-i>maxlen) MaxLen=j-i; } } } returnMaxLen; }}
Of course, we can also use a method of low time complexity, such as the use of dynamic programming, the substring of the back string is also a palindrome, such as P[i,j] (to start with the J end of the substring) is a palindrome string, then P[i+1,j-1] is a palindrome string. So the longest palindrome string can be decomposed into a series of sub-problems. This requires additional space O (n^2), and the algorithm complexity is O (n^2).
First, the state equation and the transfer equation are defined:
P[i,j]=0 indicates that the substring [i,j] is not a palindrome string. P[i,j]=1 indicates that the substring [i,j] is a palindrome string.
stringFindlongestpalindrome (string&s) {Const intLength=s.size (); intMaxlength=0; intstart; BOOLp[ -][ -]={false}; for(intI=0; i<length;i++)//Initialization Preparation{P[i][i]=true; if(i<length-1&&s.at (i) ==s.at (i+1) ) {P[i][i+1]=true; Start=i; MaxLength=2; } } for(intlen=3; len<length;len++)//Child string Length for(intI=0; i<=length-len;i++)//substring start Address { intj=i+len-1;//substring End Address if(p[i+1][j-1]&&s.at (i) = =s.at (j)) {P[i][j]=true; MaxLength=Len; Start=i; } } if(maxlength>=2) returns.substr (start,maxlength); returnNULL; }
Length of the longest palindrome substring