516. Longest Palindromic Subsequence

Posted Zzz...y

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了516. Longest Palindromic Subsequence相关的知识,希望对你有一定的参考价值。

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

判断字符串中最长的回文子串,子串不一定要连续。

动态规划的方法:

1、s[i]==s[j],s[i,j]的最长子串就是s[i+1, j-1]能构成的回文串+2;

2、不相等,也就是s[i],s[j]不能同时加入子串,s[i,j]的最长子串就是s[i, j-1]或s[i+1, j]能构成的回文串

 1 class Solution {
 2 public:
 3     int longestPalindromeSubseq(string s) {
 4         int len = s.length();
 5         if (len == 0)
 6             return 0;
 7         vector<vector<int>> dp(len, vector<int>(len));
 8         for (int i=0; i<len; ++i)
 9             dp[i][i] = 1;
10         for (int i=0; i<len; ++i) 
11             for (int j=i-1; j>=0; --j) {
12                 if (s[i] == s[j]) {
13                     dp[i][j] = dp[i-1][j+1] + 2;
14                 }
15                 else {
16                     dp[i][j] = max(dp[i-1][j], dp[i][j+1]);  
17                 }
18                      
19             }
20         return dp[len-1][0];        
21     }
22 };

 

以上是关于516. Longest Palindromic Subsequence的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode-516-Longest Palindromic Subsequence]

LC 516. Longest Palindromic Subsequence

516 Longest Palindromic Subsequence 最长回文子序列

516. Longest Palindromic Subsequence

leetcode516. Longest Palindromic Subsequence

LeetCode-Longest Palindromic Subsequence