A1040 Longest Symmetric String (25 point(s))

最长回文子串

1. 原文

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:

1
Is PAT&TAP symmetric?

Sample output:

1
11

2. 解析

3. AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include<iostream>
#include<string>
using namespace std;
int dp[1010][1010];
int main()
{
string str;
getline(cin,str);
int ans=0;
int len=0;
for (int i = 0; i < str.length(); ++i)
{
len++;
dp[i][i]=1;
ans=1;
}
for (int i = 0; i < str.length() -1 ; ++i)
{
if (str[i]==str[i+1])
{
dp[i][i+1]=1;
ans=2;
}
}
for (int L = 3; L<= len ; ++L){
for (int i = 0; L+i-1 <len ; ++i){
int j=L+i-1;
if (str[i]==str[j]&&dp[i+1][j-1]==1){
dp[i][j]=1;
ans=L;
}
}
}
cout<<ans<<endl;
return 0;
}
本文结束  感谢您的阅读
  • 本文作者: Wang Ting
  • 本文链接: /zh-CN/2019/09/03/A1040/
  • 发布时间: 2019-09-03 12:34
  • 更新时间: 2021-10-29 14:00
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!