Palindromes

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值