原文:
http://972169909-qq-com.iteye.com/blog/1084418
1、处理输入时用到了#include <ctype.h>里的3个函数,方便快捷:
if(!isalpha(buf[i]))//判断是否字母
if(isupper(buf[i])){//判断是否大写字母
str[k++] = tolower(buf[i]); //转换成小写字母
2、另外需要注意的就是
找回文时,分回文长度为奇偶两种情况处理
3、定义一个映射的数组方便处理
char buf[MAX], str[MAX];//buf存放原始字符串,str存放buf中的字母
int map[MAX]; //map映射str中字母在buf中的位置
4、使用fgets读入换行和空格,并拼接成一个字符串
while(fgets(tp, sizeof(tp), stdin)){//fgets可以读入换行符
strcat(buf,tp);
}
代码:
/*
ID: nenusb1
LANG: C++
TASK: calfflac
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>//int isalpha(int ch), isupper(),tolower()
#define MAX 20000+5
using namespace std;
char buf[MAX], str[MAX];//buf存放原始字符串,str存放buf中的字母
int map[MAX]; //map映射str中字母在buf中的位置
int main(){
freopen("calfflac.in","r",stdin);
freopen("calfflac.out","w",stdout);
//一行最多80个字符
char tp[80+5];
int len,i,j;
int maxs = 0, start = 0, end = 0,k = 0;
//************输入 **********************
while(fgets(tp, sizeof(tp), stdin)){//fgets可以读入换行符
strcat(buf,tp);
}
len = strlen(buf);
// printf("%d\n", len);
for(i=0; i<len; i++){
if(!isalpha(buf[i]))
continue;
map[k] = i;//buf[i]的字母字符保存在str[k]
if(isupper(buf[i])){
str[k++] = tolower(buf[i]);
}else{
str[k++] = buf[i];
}
} //循环结束时k就是str的长度
// printf("%d\n",k);
//*************在str中找回文,回文长度为奇偶两种情况*************
for(i=0; i<k; i++){//中心点位置 i
j=0;
while(1){
if(i-j<0 || i+j>=k || str[i-j] != str[i+j] ) {
break;
}else{
int temp = j*2 + 1;//奇数长度的回文:BBABB
if(temp > maxs){
start = i-j;
end = i+j;
maxs = temp;
}
}
j++;
}
j=0;
while(1){
if(i-j<0 || i+j+1>=k || str[i-j] != str[i+j+1] ) {
break;
}else{
int temp = (j+1)*2;//偶数长度的回文:BAAB
if(temp > maxs){
start = i-j;
end = i+j+1;
maxs = temp;
}
}
j++;
}
}
printf("%d\n",maxs);
for(i=map[start]; i<=map[end]; i++){
printf("%c",buf[i]);
}
printf("\n");
return 0;
}