"Leetcode-Interview algorithm classic-java Implementation" "05-longest palindromic Substring (maximum palindrome string)"

Source: Internet
Author: User

background

Recently began to study the algorithm, so in Leetcode do algorithm problem, the fifth question longest palindromic Substring is about palindrome string.

What is a back text string

A palindrome string is a string that is reversed before and after the string is the same as the string. For example: A,aaaa,aba,abba ...

Longest palindrome substring

Requiring the longest palindrome substring, it is necessary to traverse each substring, the time complexity is O (N2), the inferred string is not a palindrome, the time complexity is O (N), the time complexity of the algorithm is O (N3).

I just started thinking about the central extension, code such as the following:

public static string Getlongestpalindrome (String str) {if (Str.isempty () | | str.length () = = 1) {return        Str          } String longest = str.substring (0, 1); for (int i = 0; i < str.length (); i++) {//Get longest palindrome with center of I String TM              P = Helper (str, I, i);              if (Tmp.length () > Longest.length ()) {longest = TMP;              }//Get longest palindrome with center of I, i+1 tmp = helper (str, I, i + 1);              if (Tmp.length () > Longest.length ()) {longest = TMP;    }} return longest; } private static string helper (string str, int begin, int end) {while (Begin >= 0 && end <= s              Tr.length ()-1 && str.charat (begin) = = Str.charat (end)) {begin--;          end++; The String result = str.substring (begin + 1,End);      return result; }

The time complexity of the central extension method is O (N2).

After the writing has been thinking, there is no more powerful way. Can be the time complexity to kill O (N), have always wanted to think, and later on the internet searched the legendary manacher algorithm.

Let's look at the code first:

public static int[] Getpalindromelength (String str) {StringBuilder newstr = new StringBuilder ();    Newstr.append ("#");    for (int i = 0; i < str.length (); i++) {Newstr.append (Str.charat (i));    Newstr.append ("#");        } int[] rad = new Int[newstr.length ()];    The right edge of the longest sub palindrome string int right =-1;        The center of the longest sub palindrome string int id =-1;            for (int i = 0; i < newstr.length (); i++) {//define the minimum radius int r = 1;            if (I <= right) {r = math.min (right-i, rad[2 * id-i]); }//Try to get a lager radius while (i-r >= 0 && i + R < Newstr.length (            ) && Newstr.charat (i-r) = = Newstr.charat (i + R)) {r++; }//update the right edge and the center of the longest sub palindrome string if (i + R     -1> right) {           right = i + r-1;            id = i;    } Rad[i] = R;    } return rad; }

First of all. The Manacher algorithm provides a clever solution to different palindrome methods with an odd length and an even length. In each word Fu Yi inserts a special character that is not present in the original string, and normally uses "#".

In this way, either ABA type Palindrome or ABBA type palindrome. After inserting special characters, the length of the #a #b#a# and #a#b#b#a# is definitely odd, which overcomes the problem above.

The Manacher algorithm introduces an auxiliary array to record the information of the longest palindrome string centered on each character, and Rad[i] records the longest palindrome that is centered on the character Str[i]. When Str[i] is the center, this longest palindrome extends to both sides rad[i] characters.

Original string: Abbac

New string: #a #b#b#a#c#

Auxiliary Arrays: 12 1 2 5 2 1 2 1 2 1

So how does the manacher algorithm calculate the auxiliary array rad?

We calculate rad[i] from left to right, and when we calculate rad[i], Rad[j] (0<=j<i) has been calculated.

If we have the integer right, it is the most immediate edge of the longest palindrome string. And the center point of the longest palindrome substring is the ID, then there are two cases of the current pointer position I:

The first type: i<=right

So I find the symmetrical position of I relative to the center point J (2*id-i). So suppose Rad[j]<right-i. For example, with:


Then the J-centered palindrome string must be in the ID-centered palindrome string inside, and J and I about the position ID symmetry, by the definition of palindrome string. A palindrome string, in turn, is a palindrome, so the length of the palindrome string centered on I is at least the same as the palindrome string centered on J, i.e. Rad[i]>=rad[j]. Due to rad[j]<right-i. So say i+rad[j]<right. by Symmetry Rad[i]=rad[j].

Suppose Rad[j]>=right-i, by symmetry. Indicates that the I-centered palindrome string may extend beyond right, and that the part that is greater than right is not matched. So start one match from the right+1 position until the mismatch occurs, updating right and the corresponding ID and rad[i].



Another situation: I>right

Assuming I is larger than right, it means that there is no match for the palindrome of the midpoint I, and this time, it is only possible to honestly match one. When the match is complete, update the location of right and the corresponding ID and rad[i].



Summary

1. Manacher algorithm first skillfully in all characters putting inserted special characters, very good to overcome the back of the text string even length and odd length of different processing methods of the problem.

2. In fact, the complexity of the manacher algorithm is not only O (n), but obviously between O (n) and O (N2), it is the palindrome substring algorithm with the lowest time complexity.


"Leetcode-Interview algorithm classic-java Implementation" "05-longest palindromic Substring (maximum palindrome string)"

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.