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
我的思路:
1. 动态规划里面的最长回文子串题,在胡凡的算法笔记里面类型很清楚
2. 二维dp【i】【j】表示从 str【i】到 str【j】是否是回文子串,要么是要么不是(用0 1 表示)
3. dp【i】【j】根据 str【i】和 str【j】是否相等来转移:
(1) str【i】== str【j】,只要 str【i+1】到 str【j-1】是回文串,那么 str【i】到 str【j】也是回文串
(2)str【i】!= str【j,str【i】到 str【j】,肯定不是回文串
4. 边界条件: dp【i】【i】 = 1, dp【i】【i+1】= ( s【i】== s【i+1】)? 1:0
5. 按 i j 从大到小枚举无法保证dp【i+1】【j-1】已经求解,采取枚举子串长度L,再枚举左端点,右端点可知,进行求解
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int MAXN = 1010;
char str[MAXN];
int dp[MAXN][MAXN];
int main() {
cin.getline(str,MAXN);
fill(dp[0], dp[0]+MAXN*MAXN, 0);
int len = strlen(str), ans = 1;
for(int i = 0; i < len; i++){ //初始化
dp[i][i] = 1;
if(i < len-1){
if(str[i] == str[i+1]){
dp[i][i+1] = 1;
ans = 2;
}
}
}
for(int L = 3; L <= len; L++){
for(int i = 0; i+L-1 < len; i++){
int j = i+L-1;
if(str[i] == str[j] && dp[i+1][j-1] == 1){ //相等并且str[i+1]到str[j-1]也是回文串
dp[i][j] = 1;
ans = L;
}
}
}
printf("%d", ans);
return 0;
}