Medium
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"
.
講解:
Dynamic Programming | Set 12 (Longest Palindromic Subsequence)
dp[i][j]表示substring s[i, j]所包含的longest palindrome的長度。首先初始化長度為1的substring所包含的longest palindrome的長度, 也就是dp[i][i] = 1. 然后看長度為2的,長度為3的……,當(dāng)s.chatAt(i) == s.charAt(j)的時候,dp[i][j] = dp[i + 1][j - 1] + 2, 因為首尾字符串相同的話,相當(dāng)于多了2個;如果s.charAt(i) != s.charAt(j)的話,則dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]).比如字符串BABACDB的子串BABAC里面找dp[0][4]的時候,因為s.charAt(0) != s.charAt(4), 所以就等于BABA, ABAC當(dāng)中palindrome較長的, 這里都是3。
注意一下初始化的index, i是從大到小n - 1到0,j是從i + 1到n,不這么寫的話后面會很麻煩,可以記一下。
class Solution {
public int longestPalindromeSubseq(String s) {
int n = s.length();
int[][] dp = new int[n][n];
//substring of length 1 has the longest palidrome substring of length 1
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 {
//if s.chatAt(i) != s.charAt(j), then the longest palindrome length of s(i,j) is the max of s(i+1,j) ,s(i,j-1)
dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]);
}
}
}
return dp[0][n - 1];
}
}