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 };

 

posted @ 2018-04-06 15:47  Zzz...y  阅读(175)  评论(0编辑  收藏  举报