【ACM】杭电1544:Palindromes

看到这个题第一个想法就是枚举所有的子串,然后再一个一个判断是否回文。显然,在最大串长度足足有5000个字符的情况下,肯定会超时。

这时可以用另一种思想:

子串为奇数时,以一个字符为中心,依次比较这个字符左边和其对应的右边的字符是否相等,如果相等则说明这是一个回文串。

子串为偶数时,比较当前字符跟上一个字符是否相等,然后再向两边拓展,比较。

代码如下:

#include <stdio.h>
#include <string.h>

char ch[5010];
int main(int argc, char *argv[])
{
	int len = 0,i,j,k;
	while(scanf("%s",&ch) != EOF)
	{
		
		long tot = 0;
		len = strlen(ch);
		/* 以一个字符为中心向两边扩展. */
		for(i = 1 ; i < len ; ++i)
		{
			for(j = i - 1,k = i + 1; j >= 0 && k < len ; --j,++k) /* 当子串为奇数时 */
			{
				if(ch[j] != ch[k])
					break;
				++tot;
			}
			
			for(j = i - 1,k = i ; j >= 0 && k < len ; --j,++k) /* 处理子串为偶数的情况 */
			{
				if(ch[j] != ch[k])
					break;
				++tot;
			}
		}
		
		tot += len; /* 单独的一个字符也算是一个回文 */
		printf("%ld\n",tot);
	}

	return 0;
}



Problem Description
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


转载于:https://www.cnblogs.com/whongfei/archive/2012/11/11/5247017.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值