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
Example1
Input: "bbbab"
Output: 4
Explanation:
One possible longest palindromic subsequence is "bbbb".
Example2
Input: "bbbbb"
Output: 5
思路:区间型动态规划,f[i][j] 表示s[i] ~ s[j]之间最大的palindromic subsequence,递推公式是:
设dp[i][j]表示第i到第j个字符间的最长回文序列的长度(i<=j)
状态初始条件:dp[i][i]=1 (i=0:n-1)
dp[i][j]=dp[i+1][j-1] + 2 if(str[i]==str[j])
dp[i][j]=max(dp[i+1][j],dp[i][j-1]) if (str[i]!=str[j])
class Solution {
public int longestPalindromeSubseq(String s) {
int n = s.length();
int[][] dp = new int[n][n];
for(int i = 0; i < n; i++) {
dp[i][i] = 1;
}
for(int len = 2; len <= n; len++) {
for(int i = 0; i + len - 1 < n; i++) {
int j = i + len - 1;
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];
}
}