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
给你一个串,在其中找到有多少回文字串。刚开始是把所有的字串都判断了一篇
果断tle了。后来想到一个回文串真正的核心无非是中间的字符或中间两个字符,在
母串中,一旦核心确定了,然后就算下一次出现一模一样的回文串,但由于核心的
字符的位置不一样,就是位于不同的字串中,那么由子串得到的回文也不一样。
这样只要扫描一遍就能将所有的字串中的回文找出来
#include <bits/stdc++.h>
using namespace std;
char str[6000];
int judge(char *in,int m,int n)
{
int j,k,sum=0,L=strlen(in);
if(m==n)
{
for(j=m-1,k=m+1;j>=0 && k<L;j--,k++)
{
if(in[j]==in[k])sum++;
else break;
}
}
else
{
for(j=m,k=n;j>=0&&k<L;j--,k++)
{
if(in[j]==in[k])sum++;
else break;
}
}
return sum;
}
int main()
{
int i,k,j,sum,intLen;
while(scanf("%s",str)!=EOF)
{
sum=0;
intLen=strlen(str);
sum+=intLen;
for(i=1;i<intLen;i++)
{
///sum+=judge(str,i,i);
for(j=i-1,k=i+1;j>=0&&k<intLen;j--,k++)
{
if(str[j]==str[k])sum++;
else break;
}
//sum+=judge(str,i-1,i);
for(j=i-1,k=i;j>=0&&k<intLen;j--,k++)
{
if(str[j]==str[k])sum++;
else break;
}
}
cout<<sum<<endl;
}
return 0;
}