经典的 最大回文子串
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
题目大意:给定一个文本,可能有多行,字符总数不超过20000,求最长回文子串。(判断回文时只看字母,'a'-'z' 'A'-'Z',输出时按原文本输出,原文中的回车也要输出)
思路:由于数据不大,可以直接暴力,枚举回文中间的字符即可。
代码:
/*
ID: jun41821
PROG: calfflac
LANG: C++
*/
#include <iostream>
#include <cstring>
#include <fstream>
#include <algorithm>
using namespace std;
ofstream fout ("calfflac.out");
ifstream fin ("calfflac.in");
char data2[20001];
int n2,max_l=1,max_s=1,max_t=1,flag[20001]; //max_l记录最大长度 max_S为原文地址x max_t原文地址y
void expand(int,int);
int main() {
char data[20001];
int n=0;
while (fin.get(data[++n]))
if (data[n]>='a' && data[n]<='z')
{ //文件读取 一个一个读取 若是小写字母
data2[++n2]=data[n]-32; //换成大写字母存入data2中
flag[n2]=n; //记录下标
}
else if (data[n]>='A' && data[n]<='Z')
{ //大写字母
data2[++n2]=data[n];
flag[n2]=n;
}
for (int i=2;i<=n2-1;i++) { //舍弃第一位从第二位开始调用 expand为从中间延伸的函数 调用分别2次 技术和偶数的情况
expand(i-1,i+1); //数 i代表延伸位置
expand(i,i+1);
}
fout << max_l << endl;
for (int i=max_s;i<=max_t;i++) fout << data[i];
fout << endl;
fin.close();
fout.close();
return 0;
}
void expand(int x,int y) { // x y 分别代表延伸位置 若x 和 y当前位置的值相同 着令x自己剪 y自加
while (x>=1 && y<=n2 && data2[x]==data2[y]) {
x--;
y++;
}
if (y-x-1>max_l) { //若长度超过 取最大长度
max_l=y-x-1;
max_s=flag[x+1];
max_t=flag[y-1];
}
}