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
题目大意:给定一个文本,可能有多行,字符总数不超过20000,求最长回文子串。(判断回文时只看字母,'a'-'z' 'A'-'Z',输出时按原文本输出,原文中的回车也要输出)
思路:由于数据不大,可以直接暴力,枚举回文中间的字符即可。
/* ID:lijian42 LANG:C++ TASK:calfflac */ #include <stdio.h> #include <string.h> #define MAX(a,b) ((a)>(b)?(a):(b)) #define N 20010 #define LEN 81 char s[N]; char tmp[LEN]; int n; bool Isalpha(char c) { if(c>='a'&&c<='z' || c>='A'&&c<='Z') return true; return false; } bool equal(char a,char b) { if(a==b || a+'A'-'a'==b || a+'a'-'A'==b) return true; return false; } int pre(int i) { for(i--;i>=0 && Isalpha(s[i])==false;i--); return i; } int next(int i) { for(i++;i<n && Isalpha(s[i])==false;i++); return i; } void solve() { int i,j,k,h,cnt; int ans=1; int start=next(-1); for(k=1;k<n-1;k++) { if(Isalpha(s[k])==false) continue; i=pre(k); j=next(k); cnt=0; while(i>=0 && j<n && equal(s[i],s[j])) { cnt++; i=pre(i); j=next(j); } int nstart=next(i); if(2*cnt+1>ans || (2*cnt+1==ans&&nstart<start)) { ans=2*cnt+1; start=nstart; } } for(k=1;k<n-2;k++) { if(Isalpha(s[k]==false)) continue; h=next(k); if(h>=n || s[k]!=s[h]) continue; i=pre(k); j=next(h); cnt=1; while(i>=0 && j<n && equal(s[i],s[j])) { cnt++; i=pre(i); j=next(j); } int nstart=next(i); if(2*cnt>ans || (2*cnt==ans&&nstart<start)) { ans=2*cnt; start=nstart; } } printf("%d\n",ans); cnt=0; for(i=start;cnt<ans;i++) { if(Isalpha(s[i])) cnt++; printf("%c",s[i]); } } int main() { freopen("calfflac.in","r",stdin); freopen("calfflac.out","w",stdout); n=0; while(gets(tmp)) { strcpy(s+n,tmp); n+=strlen(tmp); s[n++]='\n'; } solve(); puts(""); return 0; }