L2-008 最长对称子串 (25 分)
对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定Is PAT&TAP symmetric?,最长对称子串为s PAT&TAP s,于是你应该输出11。
输入格式:
输入在一行中给出长度不超过1000的非空字符串。
输出格式:
在一行中输出最长对称子串的长度。
输入样例:
Is PAT&TAP symmetric?
输出样例:
11
题解
暴力dp
A[l][r]=A[l+1][r−1]+2A[l][r] = A[l+1][r-1] + 2A[l][r]=A[l+1][r−1]+2
公式解释
A[l][r]A[l][r]A[l][r]为字符串str[l:r]str[l:r]str[l:r]的最长对称子串长度。
对于第l位与第r位之间的字符串str[l:r]str[l:r]str[l:r],如果是对称串的话,则必满足 str[l]==str[r]str[l] == str[r]str[l]==str[r],
且str[l+1,r−1]str[l+1,r-1]str[l+1,r−1]为对称子串。
初始条件
A[i][j]=1, if i==j;A[i][j] = 1, \ if \ \ i == j;A[i][j]=1, if i==j;
A[i][j]=0, otherwise.A[i][j] = 0, \ otherwise.A[i][j]=0, otherwise.
注意读入使用getline直接读入一行,不要用cin。
代码
#include<bits/stdc++.h>
using namespace std;
int main()
{
string str = "";
getline(cin, str);
int n = str.size();
if(n == 0)
{
cout << 0 << endl;
return 0;
}
vector<vector<int> > A(n, vector<int>(n, 0));
for(int i=0;i<n;i++)
A[i][i] = 1;
int Max = 1;
for(int len=1;len<n;len++)
{
for(int l=0;l<n-len;l++)
{
int r = l+len;
if(str[l] == str[r])
{
if(A[l+1][r-1] == r - l - 1)
{
A[l][r] = A[l+1][r-1] + 2;
if(A[l][r] > Max)
Max = A[l][r];
}
}
}
}
cout << Max << endl;
return 0;
}