求串回文数

 

求串回文数

 

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)

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

 

求串回文数,标记着一种思想

这道理刚看完我就断定如果用一般的方法一定会TLE

有人说用DP,但我的DP内功并不是很深厚,于是暂时放弃这种方法

 

这题的题意很容易理解,但关键是怎么样做到不要超时

关键中的关键便是如何不要重复计算和做一些无谓的比较

 

于是不用考虑要去写一个什么判段回文的函数了

理解下回文的本质吧,如果n个字符是回文,那么里面的n-2个字符也是回文

 

用这样的思想便可以很好的避免重算

好像被我说复杂了~~~

 

AC代码:

 

#include <iostream>

#include <cstring>

using namespace std;

int main()

{

       int i,j,k,slen,p,q,sum;

       char str[5001];

       while (scanf("%s",&str)!=EOF)

       {

              sum = 0;

              slen = strlen (str);

              for (i=0;i<slen;i++) //遍历所有字符串

              {

                     for (j=0;j<=1;j++)   //对一个字符两种情况的搜索

                     {

                            p = i - j;          //左边数

                            q = i + 1;        //右边数

                            while (p>=0 && q<slen)

                            {

                                   if (str[p] == str[q])

                                   {

                                          sum++;

                                          p--;         //下一次尝试

                                          q++;              //两边各移一位

                                   }

                                   else

                                          break;

                            }

                     }

              }

              printf("%d/n",slen+sum);

       }

       return 0;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值