一、问题描述:
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:
4One possible longest palindromic subsequence is "bbbb".
Example 2:
Input:
"cbbd"Output:
2One possible longest palindromic subsequence is "bb".
二、解决思路:
经典的动态规划的问题。假设dp[i][j] 是子串i-j之间的Longest Palindromic Subsequence。那么我们可以得到动态规划的公式:
如果 s.charAt(i) == s.charAt(j) ,说明i+1至j-1之间加上i和j形成新的 Palindromic。
dp[i][j] = dp[i + 1][j - 1] + 2;
否则 dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1])
初始化为1.
三、代码:
public class Solution {
public int longestPalindromeSubseq(String s) {
int len = s.length();
int[][] dp = new int[len][len];
for (int i = len - 1; i >= 0; i--) {
dp[i][i] = 1;
for (int j = i + 1; j < len; 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][len - 1];
}
}