Given a string, you are supposed to output the length of the longest symmetric sub-string. For example, given Is PAT&TAP symmetric?
, the longest symmetric sub-string is s PAT&TAP s
, hence you must output 11
.
Input Specification:
Each input file contains one test case which gives a non-empty string of length no more than 1000.
Output Specification:
For each test case, simply print the maximum length in a line.
Sample Input:
Is PAT&TAP symmetric?
Sample Output:
11
最长回文子序列问题,用动态规划的方法去解决。按我目前的理解,与递归不同,动态规划中使用的递推是一种自底向上的方法,其含义便是把问题分割为最小子问题,用子问题的值去解决母问题。递归则是一种自顶向下的方法,在外层利用函数和方法将问题“递” 入内层,再利用边界将其“归”出来。
这题里面解决动态规划方法的关键便是找出合适的数据结构去表示状态。用二维数组dp[ i ] [ j ] = 0表示子序列 i - j 不是回文子序列,而dp[ i ][ j ] = 1 是一个回文子序列。
设子序列长度为L ,进行L ~ len 的循环,内部进行 i = 0;i + L - 1 < len 的循环 , 一直循环到最大的 L 成立为止
#include <iostream>
#include <bits/stdc++.h>
#define maxn 1010
using namespace std;
int dp[maxn][maxn];
int main()
{
char s[maxn];
fill(dp[0],dp[0]+maxn*maxn,0);
cin.getline(s,maxn); // 无法用gets函数存放带空格的字符串,引入iostream,用cin.getline(s,maxn)
//gets(s);
int len = strlen(s);
int r = 1;
for(int i = 0;i<len;i++)
{
dp[i][i] = 1;
for(int j = 0;j<len;j++)
{
if(s[i]==s[i+1]&&i<len-1)
{
dp[i][i+1] = 1;
r = 2;
}
}
}
for(int l = 3;l<=len;l++)
{
for(int i = 0;i+l-1<len;i++)
{
int j = i+l-1;
if(s[i]==s[j]&&dp[i+1][j-1]==1)
{
dp[i][j] = 1;
r = l;
}
}
}
cout<<r<<endl;
return 0;
}