Longest palindrome substring (dynamic programming method, center extension algorithm)

Source: Internet
Author: User
Tags truncated

Problem Description:

Given a string s, find the longest palindrome substring in s . You can assume that the maximum length of s is 1000.

Thinking:

Well, a palindrome! The result of sequential read and reverse reading is the same, we can use two for loop to constantly intercept the given string s, and then judge the truncated string is not a palindrome string, at the same time, using a new string result to save our intercepted and longest palindrome string.

Code:
Public String Longestpalindrome_reconstructure1 (string s) {//exceeded time limit        if (S.length () < 2) {            return s;        }        String result = s.substring (0,1);        String temp = null;        String temp1 = null;        for (int i = 0; i < s.length ()-1; i++) {            temp = null;            Temp1 = null;            for (int j = S.length (), J > i; j--) {                if (J-i < Result.length ()) break;                temp = S.substring (i, j);                Temp1 = new StringBuilder (temp). Reverse (). toString (); Reverses the truncated string                if (temp.equals (TEMP1) && temp.length () > Result.length ()) {                    result = temp;                }            }        }        return result;    }


The code above is the ability to get the longest palindrome string, but there is a clear drawback is that the time overhead is too large, so you must try to reduce the time overhead

Using the Center extension algorithm:

We observe that the two sides of the palindrome center mirror each other. Thus, a palindrome can be unfolded from its center, and only 2n-1 such a center.

You might ask, why would it be 2n-1 instead of n centers? The reason is that the center of a palindrome with an even number of letters can be between two letters (for example: the center of "ABBA" is between two B), and the time complexity is only O (n?2??).

Code:
Use the central Extension algorithm public String Longestpalindrome_reconstructure2 (string s) {///second time to refactor code if (S.length () < 2) {/        /A single character is definitely a palindrome, return s directly;        } int maxLength = 0;        int center = 0;          for (int i = 0; i < s.length (); i++) {int begin = Centerexpand (s, I, I);   The longest palindrome string length is an odd int end = Centerexpand (s, I, i + 1);                                Longest palindrome string length is even if (MaxLength < Math.max (begin, end)) {Center = i;          Centered on Center maxLength = Math.max (begin, end);  Maximum palindrome length}}//If our palindrome has an even length, then the length of the center left will be less than the length on the right 1 return s.substring (center-(maxLength    -1)/2, center + MAXLENGTH/2 + 1);        } int Centerexpand (String s, int begin, int end) {int left = begin, right = end;            while (left >= 0 && right < S.length () && S.charat (left) = = S.charat (right)) {left--;        right++;      }  Returns the longest palindrome length that can be obtained by begin,end, while extending left to right, return right-left-1; }
Using the Dynamic programming method:

Avoid unnecessary duplication of calculations when validating a palindrome. Consider the example "Ababa". If we already know that "Bab" is a palindrome, then it is obvious that "Ababa" must be a palindrome, because its left letter and the right end letter are the same.

P (i,j) = (P (i+1,j?1) and s?i?? ==s?j??)

We first initialize the one-letter and two-letter palindrome, then find all the three-letter palindrome, and so on ...

Code:
Use the dynamic programming method public    String longestpalindrome_reconstructure3 (string s) {//third time refactoring the Code        if (S.length () < 2) {//single A character is definitely a palindrome, and returns s return            s directly;        }        Boolean[][] dp = new Boolean[s.length ()][s.length ()];  Initializes a two-dimensional array whose value defaults to false        String result = s.substring (0,1);        for (int j = 0, J < S.length (); j + +) {for            (int i = 0; I <= J; i++) {                Dp[i][j] = S.charat (i) = = S.charat (j) &A mp;& (j-i <= 2 | | dp[i+1][j-1]);                if (Dp[i][j]) {                    if (j-i + 1 > Result.length ()) {                        result = S.substring (i, j + 1);                    }            }}        return result;    }

Longest palindrome substring (dynamic programming method, Central extension algorithm)

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.