Palindromes(递归)

来源:互联网 发布:access向表中加数据 编辑:程序博客网 时间:2024/05/16 05:14

问题 B: Palindromes

时间限制: 2 Sec  内存限制: 64 MB
提交: 33  解决: 6

题目描述

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.

输入

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.

输出

A single line with the number of palindrome substrings for each case.

样例输入

abaaa

样例输出

43
本题大意为求一串字符串的子串有几个为回文;解决方法,通过比较2个相邻的字符和2个相距一个字符的字符来判断子串是否为回文,其中
2个相距一个字符的字符的开头和结尾互相往外递推一个即可以推出外层是否为回文,例如aba->cabac,aba->cabad

#include <stdio.h>#include <string.h>char c[5001];int l,num;void is_Pal(int t, int k){    if(c[t] == c[k])    {        num++;//i最多到2,故只会出现2个相邻的相比较例如aba中的a和b和两个相隔一个的相比较例如aba中的a和a,所以相等必为一个回文//        while(--t>=0&&++k<l)//        {//            if(c[t]==c[k])//                num++;//            else//                return;//        }        if(--t>=0&&++k<l)        {            if(c[t]==c[k])            {                is_Pal(t,k);//递归            }        }    }}int main(){    while(scanf("%s",c)!=EOF)    {        l = strlen(c);        num = 0;        for( int i = 1; i<=2 ; i++)//i最多到2,故只会出现2个相邻的相比较例如aba中的a和b和两个相隔一个的相比较例如aba中的a和a        {            for(int j = 0; j < l-i; j++)//当i=1时,l-i限制了j的增长到最后一位数,当i=2时,l-i限制了j的增长到倒数第一位数            {                is_Pal(j,j+i);            }        }        num += l;//每一个字符本身也是也个回文,故要加上字符总数        printf("%d\n",num);    }    return 0;}

原创粉丝点击