Title Requirements:
* Solve the longest palindrome substring given a string
* String Maximum is 1000
* There is a unique longest palindrome string
Solution Ideas:
* The substring of the back character string is also a palindrome, such as p[i,j] (which means 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), the algorithm complexity is also O (n^2).
* First define the state equation and the transfer equation:
* 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])}
Code:
1 Public Staticstring Longestpalindrome (string s) {2 if(s = =NULL|| S.length () = = 1){3 returns;4 }5 intLen =s.length ();6 //flag[i][j]=true indicates that the substring i-j is a palindrome string7 Boolean[] flags =New Boolean[1000] [1000];8 intStart = 0;9 intMaxLen = 0;Ten for(inti=0; i<len; i++){ OneFlags[i][i] =true; A //two characters adjacent to each other - if(I<len-1 && S.charat (i) = = S.charat (i+1)){ -FLAGS[I][I+1] =true; theStart =i; -MaxLen = 2; - } - } + - //m stands for palindrome string length, starting from 3 + for(intm = 3; M <= Len; m++){ A for(inti = 0; I <= len-m; i++ ){ at //Compare whether the state transfer equation is met in turn - intj = I+m-1; - if(Flags[i+1][j-1] && s.charat (i) = =S.charat (j)) { -FLAGS[I][J] =true; -Start =i; -MaxLen =m; in } - } to } + - //if a palindrome substring exists the if(MaxLen >=2 ){ * returnS.substring (Start, start+maxlen); $ }Panax Notoginseng //does not exist then returns null - return NULL; the}
Leetcode-5 longest palindrome substring (dynamic planning)