516. Longest Palindromic Subsequence

来源:互联网 发布:淘宝卖家交流论坛 编辑:程序博客网 时间:2024/05/17 07:38
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

One possible longest palindromic subsequence is "bb".

Subscribe to see which companies asked this question.

思路是设dp[i, j]表示从i到j之间最大的回文子序列,分两种情况:

1、s[i] = s[j] 这种情况下dp[i, j] = dp[i + 1, j - 1] + 2

2、s[i] != s[j] 这种情况下dp[i, j] = max(dp[i + 1, j] , dp[i , j - 1])

代码:

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


0 0