ZOJ Problem Set - 2744 Palindromes(字符串二分处理的好题)

本文介绍了一种通过固定字符串的中心并向两边扩展的方法来计算一个字符串中所有回文子串的数量。这种方法适用于多种编程竞赛场景,并提供了一个具体的C++实现示例。

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

Palindromes

Time Limit: 2 Seconds      Memory Limit: 65536 KB

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 



分析:

题意:

给定若干字符串,要求统计一个字符串包含多少回文子串。

用二分法,采取分别固定左边和右边两种策略,就可以得到全部回文子串的情况。因为对于一个回文子串,它的中点位置是固定的,且是可以唯一确定子串的。其实就是先确定中点,再向两边扩展。

这种思维还是很好的,是个好题。

ac代码:

#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=5000+5;
char s[maxn];


int main()
{
    int i,j;
    int Left,Right,Half;
    while(scanf("%s",s)!=EOF)
    {
        int L=strlen(s);
        int c=0;//回文子串数
        for(i=0;i<L-1;i++)//从左到右固定住最后一个字符,中心字符串在原串的右边部分
        {
            Half=(L-1-i)/2;
            if((L-1-i)%2)//如果子串的字符数是奇数
            {
                Left=Half+i;
                Right=Half+i+1;
            }
            else//如果子串是偶数个字符
            {
                Left=Half+i-1;
                Right=Half+i+1;
            }
            while(Left>=i)
            {
                if(s[Left]==s[Right])
                {
                    Left--;
                    Right++;
                    c++;//发现一个回文子串
                }
                else break;//如果不相等,立即终止,由中心向外扩散不可能会有回文串
            }
        }
         for(i=L-2;i>0;i--)//从右到左固定第一个字符,中心字符在原串的左边部分
        {
            Half=i/2;
            if(i%2)//如果字符串的字符数是奇数
            {
                Left=Half;
                Right=Half+1;
            }
            else
            {
                Left=Half-1;
                Right=Half+1;
            }
            while(Left>=0)
            {
                if(s[Left]==s[Right])
                {
                    Left--;
                    Right++;
                    c++;
                }
                else break;
            }
        }
        printf("%d\n",c+L);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值