11151 - Longest Palindrome

ProblemD: Longest Palindrome

Timelimit: 10 seconds

 

A palindrome is a string that reads the same from the left as it does from the right. For example, I, GAG and MADAM are palindromes, but ADAM is not. Here, we consider also the empty string as a palindrome.

From any non-palindromic string, you can always take away some letters, and get a palindromic subsequence. For example, given the string ADAM, you remove the letter M and get a palindrome ADA.

Write a program to determine the length of the longest palindrome you can get from a string.

Input and Output

The first line of input contains an integer T (≤ 60). Each of the next T lines is a string, whose length is always less than 1000.

For ≥90% of the test cases, string length ≤ 255.

For each input string, your program should print the length of the longest palindrome you can get by removing zero or more characters from it.

Sample Input

2
ADAM
MADAM

Sample Output

3
5
#include<stdio.h>
#include<string.h>
#define max(x,y) ((x)>(y)?(x):(y))
char s[1005];
char rs[1005];
int f[1005][1005];
int main()
{
	int t,i,j;
	scanf("%d", &t);
	getchar();
	while (t--)
	{
		memset(f,0,sizeof(f));
		gets(s);
		for (i=0;i<strlen(s);i++)   
			rs[strlen(s)-i-1]=s[i]; 
		for(i=1;i<=strlen(s);i++){
			for(j=1;j<=strlen(s);j++)
				if(s[i-1]==rs[j-1])
					f[i][j]=f[i-1][j-1]+1;
				else
					f[i][j]=max(f[i-1][j],f[i][j-1]);
		}
		printf("%d\n",f[strlen(s)][strlen(s)]);
	}
	return 0;
}


posted @ 2013-06-16 13:15  爱生活,爱编程  阅读(279)  评论(0编辑  收藏  举报