516. Longest Palindromic Subsequence

来源:互联网 发布:js获取子元素属性 编辑:程序博客网 时间:2024/06/06 06:30

1、题目描述

给一个字符串s,返回最长的回文序列长度。


2、思路

动归。

dp[i][j] refers to the maximum length of the longest palindromic subsquence of s, starting from the index i and ending at the index j.

dp[i][j] = dp[i+1][j-1] + 2, if i<j and s[i]==s[j];

dp[i][j] = 1, if i==j;

dp[i][j] = max(dp[i+1][j],dp[i][j-1]), otherwise.

bottom-up。


3、代码

    int longestPalindromeSubseq(string s) {        int len = s.size();        int dp[len][len];        for(int i=0;i<len;i++)            for(int j=0;j<len;j++)                dp[i][j]=0;                for(int i=len-1;i>=0;i--){            for(int j=i;j<len;j++){                if(i==j)                    dp[i][j]=1;                else{                    if(s[i]==s[j])                        dp[i][j]=dp[i+1][j-1]+2;                    else                        dp[i][j]=max(dp[i+1][j],dp[i][j-1]);                }            }        }        return dp[0][len-1];    }


原创粉丝点击