1 题目
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
2 解析
2.1 题意
求最长回文子串
2.2 思路
dp[i][j]表示S[i]至S[j]所表示的子串是否是回文串,是则为1,不是为0,根据S[i]是否等于S[j],可以把转移情况分为两类,
- 1 若S[i]==S[j],那么只要S[i+1]至S[j-1]是回文串,S[i]至S[j]就是回文子串;如果S[i+1]至S[j-1]不是回文子串,那么S[i]至S[j]也不是回文子串;
- 2 若S[i] != S[j], 那么S[i]至S[j]一定不是回文子串
由此得状态转移方程:
边界:dp[i][i] = 0, dp[i][i+1] = (S[i] == S[i+1])? 1 : 0
3 参考代码
#include <cstdio>
#include <cstring>
const int MAXN = 1010;
int dp[MAXN][MAXN];
char S[MAXN];
int main(int argc, char const *argv[])
{
fgets(S, MAXN, stdin);
int len = strlen(S) - 1;
int ans = 1;
for (int i = 0; i < len; ++i)
{
dp[i][i] = 1;
if(i < len - 1){
if(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;
}
}
}
printf("%d\n", ans);
return 0;
}