It is said that if you give an infinite number of cows an infinite number of heavy-duty laptops (with very large keys), that they will ultimately produce all the world's great palindromes. Your job will be to detect these bovine beauties.
Ignore punctuation, whitespace, numbers, and case when testing for palindromes, but keep these extra characters around so that you can print them out as the answer; just consider the letters `A-Z' and `a-z'.
Find the largest palindrome in a string no more than 20,000 characters long. The largest palindrome is guaranteed to be at most 2,000 characters long before whitespace and punctuation are removed.
PROGRAM NAME: calfflac
INPUT FORMAT
A file with no more than 20,000 characters. The file has one or more lines which, when taken together, represent one long string. No line is longer than 80 characters (not counting the newline at the end).SAMPLE INPUT (file calfflac.in)
Confucius say: Madam, I'm Adam.
OUTPUT FORMAT
The first line of the output should be the length of the longest palindrome found. The next line or lines should be the actual text of the palindrome (without any surrounding white space or punctuation but with all other characters) printed on a line (or more than one line if newlines are included in the palindromic text). If there are multiple palindromes of longest length, output the one that appears first.
SAMPLE OUTPUT (file calfflac.out)
11 Madam, I'm Adam
/*
ID: xinming2
PROG: calfflac
LANG: C++
*/
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <cstring>
#include <map>
#include <string>
#include <stack>
#include <ctype.h>
#include <vector>
using namespace std;
#define MAXN 20010
char s[MAXN] , c[MAXN];//s为原字符串,c为只包含所有字母且大写变小写的s的子串
int pos[MAXN];//记录c字符串中各元素在s字符串中的位置,以便输出
int main()
{
freopen("calfflac.in","r",stdin);
freopen("calfflac.out","w",stdout);
int num = 0;
int num2 = 0;
int st , en;
vector <int> f[2];//记录所有以s[i]为终点的回文串长度,显然是降序排列的
while(scanf("%c",&s[num2++])!=EOF)
{
if(isalpha(s[num2 - 1]))
{
c[num] = tolower(s[num2 - 1]);
pos[num++] = num2 - 1;
}
}
f[0].push_back(0);//i= 0时无以他为结尾的回文串,长度为0
int max = 0;//记录最大回文串长度
bool k = true;//滚动数组节约空间,每个状态只和他上一个状态有关!
for(int i = 1 ; i < num ; i++ , k = !k)//枚举以s[i]为结尾的回文串
{
f[k].clear();
for(int j = 0 ; j < f[!k].size() ; j++)//枚举前一个点的回文串长度,看是否可以继续扩展
{
if(c[i] == c[i - f[!k][j] - 1])
{
f[k].push_back(f[!k][j] + 2);
}
}
//增加新的回文串长度
f[k].push_back(1);//只取这一点,长度为1
f[k].push_back(0);//都不取,长度为0
if(f[k][0] > max)
{
max = f[k][0];//f[k][0]为所有回文串长度中的最大值
st = pos[i - f[k][0] + 1];//当前最大回文串在s中的的起始位置
en = pos[i];//当前最大回文串在s中的终止位置
}
}
printf("%d\n",max);
for(int i = st ; i <= en ; i++)
{
printf("%c",s[i]);
}
printf("\n");
return 0;
}
/*
*/