【54】516. Longest Palindromic Subsequence

516. Longest Palindromic Subsequence

Description Submission Solutions Add to List

  • Total Accepted: 126
  • Total Submissions: 328
  • Difficulty: Medium
  • Contributors: Stomach_ache

 

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".
 
Solution:动态规划
class Solution {
public:
    int longestPalindromeSubseq(string s) {
        int n = s.size();
        int dp[n][n];//dp[i][j]代表从s[i]到s[j]的最大palin长度
        for(int i = 0; i < n; i++){
            dp[i][i] = 1;//单个字符是palin
        }
        for(int j = 1; j < n; j++){//j从1开始
            //for(int i = 0; i < j; i++){
            for(int i = j - 1; i >= 0; i--){
                //if(s[i] == s[j] && i + 1 <= j - 1){
                if(s[i] == s[j]){
                    dp[i][j] = i + 1 <= j - 1 ? 2 + dp[i + 1][j - 1] : 2;//可以不连续 所以是2
                }else{
                    dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]);
                }
            }
        }
        return dp[0][n - 1];
    }
};

 

posted @ 2017-02-10 11:30  会咬人的兔子  阅读(942)  评论(1编辑  收藏  举报