题目:
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]表示S[i]至S[j]所表示的子串是否是回文子串,是则为1,不是为0。这样根据S[i]是否等于S[j],可以把转移情况分为两类:
①若S[i]=S[j],那么只要S[i+1]和S[j-1]是回文子串,S[i]至S[j]就是回文子串;如果S[i+1]至S[j-1]不是回文子串,则S[i]至S[j]一定不是回文子串。
②若S[i]!=S[j],那S[i]至S[j]一定不是回文子串。
由此可以写出状态转移方程
边界dp[i][i]=1,dp[i][i+1]=(S[i]==S[i+1])?1:0 。
上述摘自该博主的思路:https://blog.csdn.net/qq_42265608/article/details/89514122
代码如下:
#include<stdio.h>
#include<cstring>
#include<map>
#include<algorithm>
#include<iostream>
using namespace std;
char s[1005];
int dp[1005][1005];
int main() {
scanf("%[^\n]", s);
int len = strlen(s), ans = 1;
fill(dp[0], dp[0] + 1005*1005, 0);
for (int i = 0; i < len; i++) {
dp[i][i] = 1;
if (i < len - 1 && s[i] == s[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 (s[i] == s[j] && dp[i + 1][j - 1] == 1) {
dp[i][j] = 1;
ans = L;
}
}
}
cout << ans;
}