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