计算字符串中回文的个数。

题目:

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';
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值