# PAT 甲级 1040 Longest Symmetric String (25分)

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] = \begin{cases} dp[i+1][j-1],s[i] = s[j] \\ 0,s[i]\neq s[j] \end{matrix}$

$dp[i][i] = 1 ,dp[i][i+1] = 1(s[i] = s[i+1])$

#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;
}


• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 打赏

打赏

时间领主大锤

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 举报
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文

11-25 191