Palindrome(Manacher)
Posted 0xiaoyu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Palindrome(Manacher)相关的知识,希望对你有一定的参考价值。
Andy the smart computer science student was attending an algorithms class when the professor asked the students a simple question, “Can you propose an efficient algorithm to find the length of the largest palindrome in a string?”
A string is said to be a palindrome if it reads the same both forwards and backwards, for example “madam” is a palindrome while “acm” is not.
The students recognized that this is a classical problem but couldn’t come up with a solution better than iterating over all substrings and checking whether they are palindrome or not, obviously this algorithm is not efficient at all, after a while Andy raised his hand and said “Okay, I’ve a better algorithm” and before he starts to explain his idea he stopped for a moment and then said “Well, I’ve an even better algorithm!”.
If you think you know Andy’s final solution then prove it! Given a string of at most 1000000 characters find and print the length of the largest palindrome inside this string.
Input
Your program will be tested on at most 30 test cases, each test case is given as a string of at most 1000000 lowercase characters on a line by itself. The input is terminated by a line that starts with the string “END” (quotes for clarity).
Output
For each test case in the input print the test case number and the length of the largest palindrome.
Sample Input
abcbabcbabcba
abacacbaaaab
END
Sample Output
Case 1: 13
Case 2: 6
题意:
求回文串最大长度
代码:
马拉车(Manacher算法),字符串算法的代码总是那么花里胡哨,,
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 #include <string.h> 5 6 using namespace std; 7 8 char b[2000005]; //处理之后的字符串至少是原来的两倍大 9 int p[2000005]; 10 11 int manacher(int len) 12 13 int id, re, maxx, i; 14 re = 0; 15 maxx = 0; 16 for(i=1;i<len;i++) 17 18 if(maxx > i) p[i] = min(p[2 * id - i], maxx - i); 19 else p[i] = 1; 20 while(b[i - p[i]] == b[i + p[i]]) 21 22 p[i]++; 23 24 if(maxx < p[i] + i) 25 26 id = i; 27 maxx = p[i] + i; 28 29 re = max(re, p[i] - 1); 30 31 return re; 32 33 34 int main() 35 36 int len, i, j, re, coun; 37 char a[1000055]; 38 coun = 1; 39 while(~scanf("%s", a)) 40 41 memset(p, 0, sizeof(p)); 42 if(strcmp(a, "END")==0) break; 43 len = strlen(a); 44 b[0] = ‘$‘; 45 b[1] = ‘#‘; 46 j = 2; 47 for(i = 0; i < len; i++) 48 49 b[j++] = a[i]; 50 b[j++] = ‘#‘; 51 52 b[j] = ‘\0‘; 53 len = j; 54 re = manacher(len); 55 printf("Case %d: %d\n", coun++, re); 56 57 return 0; 58
以上是关于Palindrome(Manacher)的主要内容,如果未能解决你的问题,请参考以下文章