1040 Longest Symmetric String

1040 Longest Symmetric String
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]表示str[i]到str[j]所表示的字串是否是回文字串。只有0和1
递推方程:
当str[i] == str[j] : dp[i][j] = dp[i+1][j-1]
当str[i] != str[j] : dp[i][j] =0
首先初始化dp[i][i] = 1, dp[i][i+1],把长度为1和2的都初始化好,然后从L = 3开始一直到 L <= len 根据动态规划的递归方程来判断。

#include<cstdio>
#include<cstring>
#include<algorithm> 
using namespace std;
const int maxn=1010;
int dp[maxn][maxn]={0};
char str[maxn];
int main(){
    fgets(str,maxn,stdin);
    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){
                dp[i][j]=1;
                ans=l;
            }
        }
    }
    printf("%d",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/chenyutingdaima/article/details/82016328