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".
下面是花哥的答案,本质上是从le = 1拓展到le = n - 1,什么是le呢?le是i和j加起来占的位置,
i是左起index,j是右边end的index,我们通过比较这两者是不是相等来扩展更新dp数组,dp数组的含义是index从i到j中的最长的palin subsequence,所以理应从长度1开始
class Solution { public int longestPalindromeSubseq(String s) { int n = s.length(); int[][] dp = new int[n][n]; for(int le = 1; le <= n; le++){ for(int i = 0; i <= n - le; i++){ int j = i + le - 1; if(i == j) { dp[i][j] = 1; continue; } if(s.charAt(i) == s.charAt(j)) dp[i][j] = 2 + dp[i+1][j-1]; else dp[i][j] = Math.max(dp[i+1][j], dp[i][j-1]); } } return dp[0][s.length() - 1]; } }
class Solution { public int longestPalindromeSubseq(String s) { int[][] dp = new int[s.length()][s.length()]; for(int i = s.length() - 1; i >= 0; i--){ dp[i][i] = 1; for(int j = i + 1; j < s.length(); j++){ if(s.charAt(i) == s.charAt(j)) dp[i][j] = 2 + dp[i + 1][j - 1]; else dp[i][j] = Math.max(dp[i+1][j], dp[i][j-1]); } } return dp[0][s.length() - 1]; } }