​welcome to my blog​

LeetCode 516. Longest Palindromic Subsequence (Java版; Meidum)

题目描述

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

第一次做, 动态规划 核心:1) dp[i][j]表示[i,j]上的最长回文子串 2) 根据递推公式中的依赖关系可知, 需要从下往上, 从左往右遍历

class Solution {
public int longestPalindromeSubseq(String s) {
/*
dp[i][j]表示s[i,j]上的最长回文子序列长度
i相当于左边界, j相当于右边界
dp[i][j] = dp[i+1][j-1] + (s[i]==s[j]?1:0)
*/
int n = s.length();
int[][] dp = new int[n][n];
for (int i = 0; i < n; i++) {
dp[i][i] = 1;
}
for (int i = n - 1; i >= 0; i--) {
for (int j = i + 1; j < n; j++) {
if (s.charAt(i) == s.charAt(j)) {
dp[i][j] = dp[i + 1][j - 1] + 2;
} else {
dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]);
}
}
}
return dp[0][n - 1];

}
}