第八周:[Leetcode]516. Longest Palindromic Subsequence

来源:互联网 发布:安装Linux命令行模 编辑:程序博客网 时间:2024/06/05 12:48

Given a string s, find the longest palindromic subsequence’s length in s. You may assume that the maximum length of s is 1000.
Example 1:
Input:
“bbbab”
Output:
4
One possible longest palindromic subsequence is “bbbb”.
Example 2:
Input:
“cbbd”
Output:
2


dp方法:数组dp[i][j]代表i到j的子字符串中回文子序列的最长长度,状态转移方程为:
若s[i]==s[j],dp[i][j] = dp[i+1][j-1]+2;
否则dp[i][j] = max(dp[i + 1][j],dp[i][j - 1])。


class Solution {public:    int longestPalindromeSubseq(string s) {        int l = s.length();        int dp[l][l] = {1};        for(int i = l - 1;i >= 0 ;i--){            dp[i][i] = 1;            for(int j = i + 1;j < l;j++){                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][l - 1];    }};
0 0