码迷,mamicode.com
首页 > 其他好文 > 详细

LC 516. Longest Palindromic Subsequence

时间:2019-02-11 12:26:57      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:mis   oss   possible   ble   i++   span   lse   nbsp   fas   

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

 

Runtime: 128 ms, faster than 59.09% of C++ online submissions for Longest Palindromic Subsequence.
Memory Usage: 90.5 MB, less than 0.79% of C++ online submissions for Longest Palindromic Subsequence.
 
 
class Solution {
public:
  int longestPalindromeSubseq(string s) {
    int N = s.size();
    vector<vector<int>> dp(N, vector<int>(N,0));
    for(int i=0; i<N; i++) {
      dp[i][i] = 1;
    }   
    for(int gap=1; gap<s.size(); gap++) {
      for(int i=0; i<N; i++) {
        int j = i+gap;
        if(i+gap >= N) continue;
        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][N-1];
  }
};

 

LC 516. Longest Palindromic Subsequence

标签:mis   oss   possible   ble   i++   span   lse   nbsp   fas   

原文地址:https://www.cnblogs.com/ethanhong/p/10361246.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!