LeetCode 516. Longest Palindromic Subsequence
原题链接在这里:https://leetcode.com/problems/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".
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<len; 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 }
AC Python:
1 class Solution: 2 def longestPalindromeSubseq(self, s: str) -> int: 3 if not s: 4 return 0 5 n = len(s) 6 dp = [[0 for _ in range(n)] for _ in range(n)] 7 for i in range(n - 1, -1, -1): 8 dp[i][i] = 1 9 for j in range(i + 1, n): 10 if s[i] == s[j]: 11 dp[i][j] = dp[i + 1][j - 1] + 2 12 else: 13 dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]) 14 return dp[0][n - 1]