Longest palindrome substring (manacher algorithm template Problem) && symmetric string problem

Source: Internet
Author: User

Manacher: can solve the longest palindrome problem.

Algorithm: 1. first, Add the string to the left and right of each character #, and in the s0 location to add *(if the string itself contains these, then replaced by non-occurrences of the character), the length of the string is len+len+3, that is, added len+1 # and A * ; (for example: ABA becomes * #a #b#a#)

2. Get an array of P , which is based on the new string .

Get the P array: ① traverses the string from the 1~2*len, that is, from the first # to the last character (or not the last #), to get p[1]~p[2*len];

In the ② traversal process, two new variables are defined, the ID and the Mx,id tag, the position of a character, the MX tag is the farthest position that can be matched to, and the point at which the match starts is the ID. in other words: when the ID is in this position to match the palindrome, MX reaches the current farthest position , See code for detailed Action.

③p the meaning of the array: to reach a certain character, we must know that the character can be formed with the surrounding long palindrome, such as s#b#a#b#t, the middle of which a, can make a palindrome with #b#, so a position of P value is 4, that is, the p-value represents the position of the character I can give How long the Palindrome string.

④ matching method: We can see that any one of the characters P is at least 1 (oneself with their own palindrome), then we as long as s[--i]==s[++j], let p++ can, know that both do not want to wait. however, the complexity of the time is much higher, so we need to use the previously asked P array to reduce unnecessary matching.

⑤ reduce the number of matches: use MX and ID and symmetry to see the code in Detail.

The following calculation p[i], the algorithm adds two auxiliary variable ID and mx, where the ID represents the largest palindrome substring center position, MX is id+p[id], that is, the maximum palindrome substring boundary.

The key point of this algorithm is here: if MX > i, then p[i] >= MIN (p[2 * id-i], mx-i).

The specific code is as Follows:

if (mx > I) {      p[i] = (p[2*id-i] < (mx-i) p[2*id-i]: (mx-i));} Else {       1;}

When Mx-i > p[j], the palindrome string centered on s[j] is contained in a palindrome string centered on s[id], because I and J are symmetric, the palindrome string centered on s[i] is necessarily contained in a palindrome string centered on s[id], so there must be p[i] = p[j], See.

When p[j] > mx-i, the palindrome string centered on s[j] is not completely contained in a palindrome string centered on s[id], but based on symmetry, it is known that the part surrounded by the two green boxes is the same, that is, the palindrome string centered on the s[i], and its right will expand to the position of MX at Least. , which means p[i] >= mx-i. As to whether the post-mx part is symmetrical, it is only one Match.

For the case of MX <= i, p[i] can not be made more assumptions, only p[i] = 1, and then to match the



The code is as follows:  1 void manacher ()//manacher function  2 {   3     int Len=strlen (s);   4 for     (int i=len;i>=0;--i)//expand s, Middle Add #, start with *  5     {   6         s[i+i+2]=s[i];   7         s[i+i+1]= ' # ';   8     }   9     s[0]= ' * ';  Ten     int id,mx=0;  When an MX representative is centered on an id, it reaches the farthest position of one for     (int i=1;i<len+len+1;++i) and     {         mx>i) p[i]=min (p[2*id-i ],mx-i); If the farthest position is greater than the current match, then p[i] takes min (p of the symmetric point of the id, reaches the farthest distance-i), or         else p[i]=1;//if i is on the right of mx, then p[i]=-1;         [s[i-p[i]] = = S[i+p[i]]) ++p[i];   Judge I palindrome length         if (i+p[i]>mx)//see if you want to update the farthest distance, if you want, this point as the Center. +         {             id=i;19             mx=p[i]+i;20         }21     }  22}


Symmetric string problems

Calculates the length of the most frequently symmetric substring of a given string, such as the longest symmetric substring in "iqiyi" is "i", the longest symmetric substring of "iqiyiyiq" is "qiyi" and "qyiq", the length is 4, and the given string is a combination of plain lowercase letters.

Input

The input data is a single-line string, containing only lowercase letters and no spaces in the Middle.

Output

The length of the longest symmetric string.

Sample input

Iqiyiyiq

Abccba

Sample output

4

3

#include <iostream>    #include <string>       using namespace std;int main () {string s;while (getline (cin, S) {string S1 = "*#"; for (int i = 0; i < s.size (); I++) {s1 + = s[i];s1 + = ' # ';} int *p = new Int[s1.size ()];for (int i = 0; i<s1.size (); i++) p[i] = 1;int id = 0;int mx = 0;for (int i = 1; i < S1.S Ize ();  i + +) {if (mx>i) p[i] = (p[2*id-i]>mx-i?mx-i:p[2*id-i]), Else p[i] = 1;while (s1[i-p[i] [= s1[i + p[i]]) p[i]++;if (i + p[i] > Mx) {id = i;mx = p[i] + i;}} int max = 0;for (int i = 1; i < s1.size (); i + +) {if (p[i]>max) max = p[i];} If ((max-1)%2==0) cout << (max-1)/2<< endl;else cout << (max-1)/2+1<< endl;} Return 0;}





1. http://acm.hdu.edu.cn/showproblem.php?pid=3068

Time-out error is used several times strlen (), correction method int N=strlen (); call again with a constant can not time out

2. The main idea of the Topic:

Given a string, containing only lowercase letters, the length of the longest palindrome substring, The simplest problem of finding palindrome substrings,

The longest palindrome

Time limit:4000/2000 MS (java/others) Memory limit:32768/32768 K (java/others)
Total submission (s): 4275 Accepted submission (s): 1417


Problem description gives a string s that consists only of lowercase English characters a,b,c...y,z, seeking the length of the longest palindrome in S.
Palindrome is the same as the inverse of the string, such as aba, abba, etc.


Input has multiple sets of case, no more than 120 groups, each set of input is a line of lowercase English characters a,b,c...y,z string s
Between two sets of case separated by a blank line (the empty line is not processed)
String length len <= 110000


Output an integer x for each row, corresponding to a set of case, representing the longest palindrome length contained in the string for the group Case.


Sample Input
Aaaaabab


Sample Output
4

3

#include <stdio.h> #include <string.h> #include <algorithm> using namespace std;  #define MAXX 20000050 Char str[2*maxx];  Char s[maxx];  int p[maxx];      void Manacher (int *p,char *str,int len) {int mx=0;      int idx=0;          For (int i=1; i<len; i++) {p[i]=mx>i?min (p[2*idx-i],mx-i): 1;          While (str[i+p[i]]==str[i-p[i]]) p[i]++;              If (i+p[i]>mx) {mx=i+p[i];          idx=i; }}} int main () {while (scanf ("%s", s)!=eof) {int Nn=strlen (s);//need to define a variable nn, if each call strlen (s), the time          As long as the President int n=2*nn+2;          Str[0]= ' $ ';              For (int i=0; i<=nn; i++) {str[2*i+1]= ' # ';          str[2*i+2]=s[i];          } manacher (p,str,n);          int ans=1;          For (int i=0; i<n; i++) Ans=max (ans,p[i]);        printf ("%d\n", ans-1);  } return 0;   }/* AAAA abab */

Longest palindrome substring (manacher algorithm template Title) && symmetric string problem

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.