zoj 2744 Palindromes (求回文子序列的个数)

本文介绍了如何计算给定字符串中所有连续子串的回文子序列数量,并提供了实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

链接:zoj 2744

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


求回文子序列的个数,如 aba 的回文子序列有 a, b, a, aba.

解析:一个序列,若一个序列中间的两个连续字符或三个连续字符的子序列不回文,则其肯定不回文

代码:

#include<stdio.h>
#include<string.h>
int main()
{
    char s[5005];
    int i,l,r,t,n;
    while(scanf("%s",s)!=EOF){
        t=n=strlen(s);
        for(i=0;i<n;i++){
            l=i;
            r=i+1;
            while(l>=0&&r<n){
                if(s[l--]==s[r++])
                    t++;
                else
                    break;
            }
        }
        for(i=0;i<n;i++){
            l=i;
            r=i+2;
            while(l>=0&&r<n){
                if(s[l--]==s[r++])
                    t++;
                else
                    break;
            }
        }
        printf("%d\n",t);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值