516. Longest Palindromic Subsequence

来源:互联网 发布:淘宝加盟要多少钱 编辑:程序博客网 时间:2024/06/05 03:57

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".

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

0 0
原创粉丝点击