Given a string S, find the longest palindromic substring in s. The maximum length of S is assume, and there exists one unique longest palindromic substring.
Idea One: (Time-out) simply intercept the length of a string that is long, which is decremented, to determine whether it is a palindrome string. The first palindrome that satisfies the requirement is the longest.
Public classSolution { Publicstring Longestpalindrome (string s) {intm=s.length (); String ans=NULL; if(m==0) returns; if(m==1) returnBS; for(intlength=m;length>=0;length--){ for(inti=0;i+length-1<m;i++) {ans=s.substring (i,i+length-1); if(ispalindromic (ans))returnans; } } returnans; } Public Static Booleanispalindromic (String l) {intk=l.length (); for(inti=0;i<k/2;i++){ if(L.charat (i)!=l.charat (k-1-i))return false; } return true; }}
View Code
IDEA two: Dynamic planning. Dp[i][j]=true when Dp[i+1][j-1]=true&&s.charat (i) ==s.charat (j);
Public classSolution { Publicstring Longestpalindrome (string s) {intn =s.length (); intStart = 0; intMaxLength = 1; BooleanDp[][] =New Boolean[N+1] [N+1]; for(inti = 0; I < n; i++) {Dp[i][i]=true; } for(inti = 0; i < n-1; i++) { if(S.charat (i) = = S.charat (i+1) ) {Dp[i][i+1] =true; Start=i; MaxLength= 2; } } for(intlen = 3; Len <= N; len++) { for(inti = 0; i < n-len+1; i++) { intj = i+len-1; if(S.charat (i) = = S.charat (j) && Dp[i+1][j-1]) {Dp[i][j]=true; Start=i; MaxLength=Len; } } } returnS.substring (Start, start+maxLength); } }
View Code
Idea Three: Http://articles.leetcode.com/2011/11/longest-palindromic-substring-part-ii.html This method is the most efficient, the current level still can't think of such a method.
Leetcode 5:longest palindromic Substring (Longest palindrome)