LeetCode 516. Longest Palindromic Subsequence

原题链接在这里:https://leetcode.com/problems/longest-palindromic-subsequence/?tab=Description

题目:

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

题解:

DP问题. dp[i][j]表示从i到j的最大subsequence长度.

状态转移. 如果s.charAt(i) == s.charAt(j), dp[i][j] = dp[i+1][j-1] + 2. 所以i要从大往小变化.

否则dp[i][j] = Math.max(dp[i+1][j], dp[i][j-1]). 要么去头 要么去尾, 看剩下段的最长subsequence长度.

初始化 dp[i][i] = 1.

答案., dp[0][len-1].

Time Complexity: O(n^2), n = s.length().

Space: O(n^2).

AC Java:

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

 类似Longest Palindromic Substring, Valid Palindrome III.

你可能感兴趣的:(LeetCode 516. Longest Palindromic Subsequence)