题目:
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
解答:
#include <stdio.h>
#include <string.h>
void getstr(char [], int, int, char []);
int palindrome(char []);
void inverse(char [], char []);
int main()
{
int i,j;
int sum,len;
char str[50];
char temp[50];
printf("please input string : ");
gets(str);
sum = strlen(str);
len = sum;
for(j=2; j<=len; j++) //把每一种字母组合都取出来,先是2个的字母组合,然后是3,4……
{
i = 0;
while(str[i+j-1]!='/0'){
getstr(str, i, j, temp); //把字母组合取出来,从str的第i位开始取j个字符,存在temp里
if(palindrome(temp)){ //如果是temp是回文的话,总数加1
sum++;
//printf("%s/n",temp); //去掉注释,可以显示除了单个字符以外的回文字符串
}
//printf("%s/n",temp); //去掉注释,可以显示所有的子字符串
i++;
}
}
printf("sum = %d/n",sum);
}
void getstr(char str[], int i, int j, char temp[])
{
int k;
for(k=0; k<j; k++)
{
temp[k] = str[i++];
}
temp[k] = '/0';
}
int palindrome(char temp[]) //把字符串颠倒过来,和原字符串比较
{
char temp1[50];
inverse(temp,temp1);
if(strcmp(temp, temp1) == 0)
return 1;
else
return 0;
}
void inverse(char temp[], char temp1[]) //颠倒字符串
{
int i,j,len;
len = strlen(temp);
for(i=0,j=len-1; i<len; i++,j--)
{
temp1[i] = temp[j];
}
temp1[i] = '/0';
}