NEUOJ-1235 Palindrome Substring
![](http://b1.edu.qzone.qq.com/ac/b.gif)
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
character
aaaaba
hello
Sample Output
5
5
2
之前在看矩阵链乘法和最长公共子序列,受到这两种算法的启发,试着用长度来做。。
在初始化那一块浪费了比较多时间所以效率有点低。。。时间复杂度O(N^2),很简洁漂亮的做法。。学习了。。
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),很简洁漂亮的做法。。学习了。。