您的位置:首页 > 大数据 > 人工智能

【最长回文字串】Calf Flac 最长的回文 (Usaco_Training 1.3)

2012-10-13 21:59 453 查看
Calf Flac
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




这一题不用多说,基本代码都能写出来,一个二重循环,然后在一重循环判断即可,代码很简单,但是时间效率几乎接近O(n3)!!毫无疑问,是不能AC的

一种解决的方法就是枚举中间节点,然后向两边扩展即可,这样时间效率就接近O(n2)了,再说说具体实现

相信你已经知道了要分回文串长度是奇数还是偶数来处理。如果是奇数,中间点是i,那么需要比较的点就是i-j和i+j(j从1开始增加),计数器从1开始计数(1是指中间那个不需要比较的),每次+2;如果是偶数,那么需要比较的点就是i-j和i+j+1(j从0开始),计数器从0开始,每次+2

剩下的还要提醒一点,由于最后要按照原文输出,也就意味着包括换行符!!!所以我建议每读一行,就加上一个"\n",这样就能巧妙处理了

C++ Code

/*
ID: jiangzh15
TASK: calfflac
LANG: C++
*/
//   http://oijzh.cnblogs.com #include<fstream>
#include<string>
#include<cctype>
using namespace std;

string s;
struct node{char ch;int num;}a[20010];
int len[20010];

int main()
{
ifstream fin("calfflac.in");
ofstream fout("calfflac.out");
string temp;
while(getline(fin,temp)) {s+=temp;s+="\n";}
int c=0;
int i,j;
for(i=0;i<s.length();i++)
if(isalpha(s[i]))
{
a[c].ch=toupper(s[i]);
a[c].num=i;
c++;
}
int l,r,sum,maxx=0;
for(i=0;i<c;i++)//枚举中间点
{
j=1;sum=1;
while(i-j>=0 && i+j<c)//处理奇数情况
{
if(a[i-j].ch==a[i+j].ch)
{
sum+=2;
if(sum>maxx)
{
maxx=sum;
l=i-j;r=i+j;
}
}
else break;
j++;
}
j=0;sum=0;
while(i-j>=0 && i+j+1<c)//处理偶数情况
{
if(a[i-j].ch==a[i+j+1].ch)
{
sum+=2;
if(sum>maxx)
{
maxx=sum;
l=i-j;r=i+j+1;
}
}
else break;
j++;
}
}
fout<<maxx<<endl;
for(i=a[l].num;i<=a[r].num;i++) fout<<s[i];
fout<<endl;
fin.close();fout.close();
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: