Leetcode 5:longest palindromic Substring (Longest palindrome)

Source: Internet
Author: User

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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.