A regular palindrome is a string of numbers or letters that is the same forward as backward. For example, the string "ABCDEDCBA" is a palindrome because it is the same when the string is read from left to right as when the string is read from right to left.
Now give you a string S, you should count how many palindromes in any consecutive substring of S.
Input
There are several test cases in the input. Each case contains a non-empty string which has no more than 5000 characters.
Proceed to the end of file.
Output
A single line with the number of palindrome substrings for each case.
Sample Input
aba
aa
Sample Output
4
3
Author: LIU, Yaoting
Source: Zhejiang Provincial Programming Contest 2006
//1843514 2009-04-25 09:21:07 Time Limit Exceeded 2744 C++ 1001 24612 Wpl
//1843524 2009-04-25 09:39:08 Accepted 2744 C++ 760 24612 Wpl
/*
最好边做边计算sum如果单独出来计算会超时
*/
#include <iostream>
#define MAX 5001
using namespace std;
bool mark[MAX][MAX];
char str[MAX];
int main()
{
int i,j,len,r;
while(scanf("%s",str+1)!=EOF)
{
int sum=0;
len=strlen(str+1);
for(r=1;r<=len;r++)
for(i=1;i<=len-r+1;i++)
{
j=i+r-1;
if(i==j) //注意将这种情况统计在里面
{
mark[i][j]=1;
sum++;
continue;
}
if(j==i+1&&str[i]==str[j]) //注意将这种情况统计在里面
{
mark[i][j]=1;
sum++;
continue;
}
mark[i][j]=0;
if(str[i]!=str[j])
mark[i][j]=0;
else
{
if(mark[i+1][j-1])
{
mark[i][j]=1;
sum++;
}
else
mark[i][j]=0;
}
}
printf("%d\n",sum);
}
return 0;
}

0 评论:
发表评论