#include <iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int main()
{
char s[5000];
int p, i, Half, Left, Right, Count;
while( cin>>s )
{
i = strlen(s);
Count = 0;
for(p=0; p<=i-1; p++)
{
Half = ((i-1)-p) / 2;
if( ((i-1)-p)%2 == 0 )
{
Left = p + Half - 1;
Right = p + Half + 1;
}
else
{
Left = p + Half;
Right = p + Half + 1;
}
while( Left >= p )
{
if( s[Left] == s[Right])
{
Count++;
Left--;
Right++;
}
else
{
break;
}
}
}
for(p=i-2; p>=1; p--)
{
Half = p / 2;
if( p%2 == 0 )
{
Left = Half - 1;
Right = Half + 1;
}
else
{
Left = Half;
Right = Half + 1;
}
while( Left >= 0 )
{
if( s[Left] == s[Right] )
{
Count++;
Left--;
Right++;
}
else
{
break;
}
}
}
printf("%d\n",Count + i);
}
return 0;
}
同学的代码
#include<bits/stdc++.h>
using namespace std;
char s[5005];
int main()
{
int len,m=0,cnt=0,x,y;
while(fgets(s,sizeof(s),stdin))//读取完整的一行放入是s1中
{
cnt=0;
len=strlen(s);
for(int i=0;i<len;i++)
{
for(int j=0;i-j>=0&&i+j<len;j++)
{
if(s[i-j]!=s[i+j])break;
cnt++;
}
for(int j=0;i-j>=0&&i+j+1<len;j++)
{
if(s[i-j]!=s[i+j+1])break;
cnt++;
}
}
cout<<cnt-1<<endl;
}
return 0;
}