[Leetcode] Specific analysis of longest palindrome Substring

Source: Internet
Author: User

Given A stringS, find the longest palindromic substring inS. Assume that maximum length ofSis, and there exists one unique longest palindromic substring.

The examiner of the face DP problem is a psychopath.

。 (Spit Groove)

Seems to be easy out of a palindrome problem, then today carefully analyze the practice of DP!!

In order to solve my problem of DP problems to the broken heart feeling of slag. If there is an error please indicate ~


First of all. Take this problem, at least can also give an O (n^3) algorithm. 2-layer for loop plus every check substring is not a palindrome.

I gave a code that must be timed out for reference.

Public String Longestpalindrome (string s) {if (s==null) return null;        String[][] dp= new string[1000][1000];        Arrays.fill (dp,1);        int max=1;        String result=s.substring (0,1); for (int i=0;i<s.length () -1;i++) {for (int j=i+1;j<s.length (); j + +) {String temp=s.substring (                I,J+1);                        if (Ifpalin (temp)) {if (Max<temp.length ()) {max=temp.length ();                    Result=temp;                } if (Max==s.length ()) return result;            }}} return result;        public Boolean Ifpalin (String s) {if (s==null) return true;        int start=0;                int End=s.length ()-1;            while (Start<end) {if (S.charat (start++)!=s.charat (end--)) {return false;    }} return true; }


This is obviously not enough. How to optimize? You'll think of such a disgusting problem. DP that's for sure.

Then we should analyze palindrome. The whole situation must be taken into account.

↑ above Naive method timeout reason is because: each cycle, have to see the current substring is not a palindrome, then how to solve such repetitive work?

Through the analysis of the nature of palindrome. We can see: Suppose that the middle of a string sub is a palindrome, assuming that the sub two is the same character. Then as a whole is also a palindrome.

Like what:

Abcdcba:d is a palindrome, CDC then is a palindrome. Suppose you think about it a little bit more. CDC is a palindrome. Two side B is the same, BCDCB is also a palindrome. Gee, then ABCDCBA is a palindrome.

We know the answer directly through the last example. This is a special case, so what is good for the general situation? So the first idea is based on the following reasoning:

We affirm a dp[][] to store the state. For Dp[i][j], the meaning is s.substring (i,j+1) is not a palindrome.

(1) Since we don't know where the center is. Expand outward to get the answer.

Then to each character as the center, outward expansion, save a maximum amount, the problem is conquered!

We have to initialize the DP, the single character is, so dp[i][i]=true.

But there is a situation. ABCDDCBA, the middle is two. Not one, which can also make a palindrome, how to do this.

Actually. Let's take a look at S.charat (i) ==s.charat (i+1), assuming it is a palindrome. We'll set dp[i][i+1]=true.

With the basic case, we 1-layer for loop Moving center point, with two pointers start,end, respectively, expand the two cases, to analyze palindrome. You can find the maximum value.

The code is as follows:

 Public String Longestpalindrome (string s) {if (s==null) return null;        Boolean[][] dp= New Boolean[s.length ()][s.length ()];        Define DP[I][J] is if s.substring (i,j+1) is Palindrome:int max=1;        String result=s.substring (0,1);        for (int i=0;i<s.length (); i++) {dp[i][i]=true;                } for (int i=0;i<s.length () -1;i++) {if (S.charat (i) ==s.charat (i+1)) {dp[i][i+1]=true;                Result=s.substring (i,i+2);            max=2;  }} for (int i=1;i<s.length () -1;i++) {int start=i-1,end=i+1; The situation of ABA while (Start>=0 && end<=s.length ()-1) {if (Dp[i][i] && S.charat (St                    ART) ==s.charat (end) {dp[start][end]=true;                        if (max<end-start+1) {max=end-start+1;                    Result=s.substring (start,end+1);             }} else {   Break             } start--;end++;  } start=i-1;end=i+2; ABBA situation while (Start>=0 && end<=s.length ()-1) {if (dp[i][i+1] && S.charat                    (start) ==s.charat (end) {dp[start][end]=true;                        if (max<end-start+1) {max=end-start+1;                    Result=s.substring (start,end+1);                }} else{break;             } start--;end++;            }} return result; }

The above code is a bit verbose. Should be able to simplify, I am more lazy. If you understand the meaning, it's good to do it!

(2) the solution above is actually not quite a DP, so let's consider the real DP solution, but this is sometimes very difficult to figure out. Think more about it.

At least. Suppose you see this. Be patient and look at some more. Will certainly understand the process of DP solution:

DP's idea is to use the results that were once made as a basis, and then derive the new results. (2) The idea is: the use of the nature of palindrome, assuming that the inference dp[i][j] is not a palindrome. So what does it have to have?

The answer is:

1. S.charat (i) ==s.charat (j)

2. Dp[i+1][j-1] is True

( This represents the current s.substring (i,j+1) to the inside to shrink a substring is a palindrome, a bit around. For example: Abccbfee, suppose i=0,j=5, or abccbf,dp[i][j] means ABCCBF is not a palindrome, based on previous results, assuming S.charat (i) ==s.charat (j), and. BCCB is also a palindrome, then Dp[i][j] is true. In this example a!=f, although Dp[i+1][j-1] (BCCB) is a palindrome, that is not true)


So the essence of DP is manifested: through the previous results, derivation now!

There is a key point. Is the DP's notation. In the afternoon I printed out the DP array, and the horizontal axis I moved forward from behind. J is from I to the last. 1 means true, a palindrome, 0 instead.

DP inside quite a lot is from the back, of course, we can not remember the results, but to clarify why do so.


The central majority of palindrome should be in the central position, so. We are able to take advantage of the previous results by moving forward from behind. (It's the same as before, just a change in the number of loops)

However, the above conditions are not enough! Suppose that dp[i+1][j-1] is false.

But when the characters I and J are consistent, and the distance is less than or equal to 2 , it is a palindrome, because there are only 3 cases: A (i=j) AA (i=0,j=1) a*a (i=0,j=2) * denotes random characters. So we can be a palindrome.

Then I do not move, J go, beyond the distance of 2, also may encounter and I the same character, this time is not a palindrome ? It depends on dp[i+1][j-1] is not a palindrome, assuming it is. Record whether the current maximum length is inferred.

Replace the longest string, assuming it is over.

Looking at the second picture, the three 1, in fact, is the derivation process of abccbadd in the sample, when the i=2 cycle. j=2. It's a palindrome, record. i=2, j=3, "CC" is a palindrome, continue. "CCB" is not a palindrome,

Above is all the analysis, suggested to see the article of the children's shoes self-deduction process. Just understand why this is done, talent really understand DP. and write out a clean, refined DP code.

: The following code was seen from the great God and brought over.

    Public String Longestpalindrome (string s) {          if (S==null | | s.length () ==1) return s;        Boolean[][] dp= New Boolean[s.length ()][s.length ()];        Define DP[I][J] is if s.substring (i,j+1) is palindrome:        int max=0;        String result=s.substring (0,1);        for (int i=s.length () -1;i>=0;i--) {for            (int j=i;j<s.length (); j + +) {                if (S.charat (i) ==s.charat (j) & & ((j-i<=2) | | dp[i+1][j-1]) {                    dp[i][j]=true;                    if (max<j-i+1) {                        max=j-i+1;                        Result=s.substring (i,j+1);        }}} return result;    }



Copyright notice: This article blog original article. Blogs, without consent, may not be reproduced.

[Leetcode] longest palindrome Substring specific analysis

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.