My first thought about this problem is that the character of a palindrome string, each of the characters (odd palindrome strings), or every two characters (even palindrome), begins to extend the analysis to both sides. In this process, the newest longest palindrome is constantly discovered. Obviously the complexity of this algorithm is O (n^2)
Class solution {public:string longestpalindrome (string s) {//Center extension method Int maxlen;int prev;int next;string result;maxlen = 0;//palindrome string is odd when for (int i = 0; i < s.size (); i++) {prev = i;next = i;while (true) {prev = prev - 1;next = next + 1;if (prev < 0 | | next > s.size () - 1) {if (next - 1) - (prev + 1) + 1 > maxlen) {maxlen = (next - 1) - (prev + 1) + 1;result.assign (S, prev + 1, maxlen);} break;} if (S[prev] != s[next]) {if (next - 1) - (prev + 1) + 1 > maxlen) {maxlen = (next - 1) - (prev + 1) + 1;result.assign (s, prev + 1, maxlen);} Break;}}} Palindrome string is even when for (Int i = 0; i < s.size (); i++) {Prev = i;next = i+1;if (Prev >= 0 && next <= s.size () - 1 && s[prev] == s[next]) {while (true) {prev = prev - 1;next = next + 1;if (prev < 0 | | next > s.size () - 1) {if (next - 1) - (prev + 1) + 1 > maxlen) {maxlen = (next - 1) - (prev + 1) + 1;result.assign (S, prev + 1, maxlen);} break;} if (S[prev] != s[next]) {if (next - 1) - (prev + 1) + 1 > maxlen) {maxlen = (next - 1) - (prev + 1) + 1;result.assign (s, prev + 1, maxlen);} Break;}}}} return result;}};
====================================================================
The second method, use DP. This is collected on the Internet.
The substring of the back character string is also a palindrome, such as p[i,j] (indicating that the substring ending with J begins with I) is a palindrome string, then P[i+1,j-1] is also 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.
P[i,i]=1
P[i,j]{=p[i+1,j-1],if (S[i]==s[j])
=0, if (S[i]!=s[j])
String Findlongestpalindrome (String &s) {const int length=s.size (); int Maxlength=0;int Start;bool P[50][50]={false };for (int i=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 (int len=3;len<length;len++)//substring length for (int i=0;i<=length-len;i++)//substring start address {int j=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) return s.substr (start,maxlength); return NULL;}
leetcode--Longest palindrome substring