NEUOJ-1235 Palindrome Substring

NEUOJ-1235 Palindrome Substring

Description

     Mourinho is a CS student studying in NEU. One day, he learns an English word 'palindrome' from a dictionary. A palindrome is a word or phrase that is the same whether you read it backwards or forwards, for example the word 'refer'.
     Mourinho is a boy who likes to think of different kinds of questions. Now he wants to the longest palindrome substring of a given string. For example, "character" is the given string. "carac" is one of the substrings of "character" which is the longest palindrome on the same time.
     Now Mourinho turns to you for help. Can you help him?

Input

     The first line contains the number of test cases T(1<=T<=200). Each of the following T lines contains a test string. The string only contains lower-case letter.(the length of the string <=500)

Output

     Output the length of the longest palindrome substring of the T test cases. Each one occupies a line.

Sample Input

3
character
aaaaba
hello

Sample Output

5
5
2

之前在看矩阵链乘法和最长公共子序列,受到这两种算法的启发,试着用长度来做。。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
 
int main()
{
     int t;
     scanf ( "%d" , &t);
     while (t--)
     {
         char s[501]; int len, a[501][501];
         scanf ( "%s" , s);len = strlen (s);
         for ( int b=0; b<len; b++) a[b][1] = 1;
         for ( int l=2; l<=len; l++)
         {
             for ( int b=0; b<=len-l; b++)
             {
                 if (s[b]==s[b+l-1])
                     a[b][l] = a[b+1][l-2] + 2;
                 else
                     a[b][l] = max(a[b+1][l-1], a[b][l-1]);
             }
         }
         printf ( "%d\n" , a[0][len]);
     }
     return 0;
}
O(n*log(n))的算法吧感觉上是~
后来问了一下陶大神。。知道了一种用最长公共子序列的方法来做,挺神奇的。。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int main()
{
     char s[502];
     int t;
     scanf ( "%d" , &t);
     while (t--)
     {
         scanf ( "%s" , s);
         int a[502][502], n= strlen (s);
         memset (a, 0, sizeof (a));
         for ( int i=1; i<=n; i++)
         {
             for ( int j=1; j<=n; j++)
             {
                 if (s[i-1]==s[n-j])
                 {
                     a[i][j] = a[i-1][j-1] + 1;
                 }
                 else
                 {
                     a[i][j] = max(a[i-1][j], a[i][j-1]);
                 }
             }
         }
         printf ( "%d\n" , a[n][n]);
     }
     return 0;
}

 在初始化那一块浪费了比较多时间所以效率有点低。。。时间复杂度O(N^2),很简洁漂亮的做法。。学习了。。
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值