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]表示s[i]到s[j]所表示的字串是否是回文字串。只有0和1
递推方程:
当s[i] == s[j] : dp[i][j] = dp[i+1][j-1]
当s[i] != s[j] : dp[i][j] =0
边界:dp[i][j] = 1, dp[i][i+1] = (s[i] == s[i+1]) ? 1 : 0
---------------------
原文:https://blog.csdn.net/liuchuo/article/details/52138902
参考代码:
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
string s;
int dp[10001][1001];
int main(){
getline(cin, s);
int ans = 1;
for(int i = 0; i < s.size(); ++i){
dp[i][i] = 1;
if(i < s.size() - 1 && s[i] == s[i + 1]) dp[i][i + 1] = 1, ans = 2;
}
for(int L = 3; L <= s.size(); ++L)
for(int i = 0; i + L - 1 < s.size(); ++i){
int j = i + L - 1;
if(s[i] == s[j] && dp[i + 1][j - 1]) dp[i][j] = 1, ans = L;
}
printf("%d\n", ans);
return 0;
}