PAT 甲级 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 ]   =  0表示子序列 i -  j 不是回文子序列,而dp[ i ][ j ] = 1 是一个回文子序列。

dp[i][j] = \begin{cases} dp[i+1][j-1],s[i] = s[j] \\ 0,s[i]\neq s[j] \end{matrix}  

dp[i][i] = 1 ,dp[i][i+1] = 1(s[i] = s[i+1]) 

设子序列长度为L ,进行L ~ len 的循环,内部进行 i = 0;i + L - 1 < len 的循环 , 一直循环到最大的 L 成立为止

#include <iostream>
#include <bits/stdc++.h>

#define maxn 1010

using namespace std;

int dp[maxn][maxn];

int main()
{
    char s[maxn];
    fill(dp[0],dp[0]+maxn*maxn,0);
    cin.getline(s,maxn);    // 无法用gets函数存放带空格的字符串,引入iostream,用cin.getline(s,maxn)
    //gets(s);
    int len =  strlen(s);
    int r = 1;
    for(int i = 0;i<len;i++)
    {
        dp[i][i] = 1;
        for(int j = 0;j<len;j++)
        {
            if(s[i]==s[i+1]&&i<len-1)
            {
                dp[i][i+1] = 1;
                r = 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;
                r = l;
            }
        }
    }

    cout<<r<<endl;
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值