ZOJ 2744 Palindromes(动态规划)

Palindromes

Time Limit: 2 Seconds      Memory Limit: 65536 KB

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

 

做了一下午的动态规划,才发现懂得只有那么一点点,大部分还是百度出来才能理解状态转移方程,这一道,算是自己思考的最多的一道吧

 令d[i][j]表示这一串字符从第i个到第j个字符组成的串是否是回文。

如果 i 到 j 组成的串字符超过了3个,则必须满足 i-1 到j-1 个字符组成的串是回文,它才有可能是回文

初始条件是:数组所有数据为0

 1 # include<stdio.h>
 2 # include<string.h>
 3 # define maxn 5001
 4 char s[maxn];
 5 bool dp[maxn][maxn];
 6 
 7 int main()
 8 {
 9     int len,ans,i,j,k;
10     while(scanf("%s",s)!=EOF)
11     {
12         len=strlen(s);
13         ans=len;
14         memset(dp,0,sizeof(dp));
15         for(k=1;k<len;k++)
16         {
17             for(i=0;i<len-k;i++)
18             {
19                 j=i+k;
20                 dp[i][j]=0;
21                 if(s[i]==s[j])
22                 {
23                     if(i+1 <j-1)
24                     {
25                         if(dp[i+1][j-1])
26                         {
27                             dp[i][j]=1;
28                             ans++;
29                         }
30                     }
31                     else
32                     {
33                         dp[i][j]=1;
34                         ans++;
35                     }
36                 }
37             }
38         }
39         printf("%d\n",ans);
40     }
41     return 0;
42 }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值