publicintlongestPalindromeSubseq(String s) {if (s ==null||s.isEmpty()) {return0; }int n =s.length();int[][] dp =newint[n][n];// init diagonal to 1, length of one char's palindrome is 1for (int i =0; i < n; i++) { dp[i][i] =1; }// fill the matrix for len = 2 -- can omit when len start from 1. add this, len start from 2// for (int i = 0; i < n - 1; i++) {// dp[i][i + 1] = s.charAt(i) == s.charAt(i + 1) ? 2 : 0;// }// fill the dp matrixfor (int len =1; len < n; len++) {for (int start =0; start + len < n; start++) {if (s.charAt(start) ==s.charAt(start + len)) { dp[start][start + len] =2+ dp[start +1][start + len -1]; } else { dp[start][start + len] =Math.max(dp[start +1][start + len], dp[start][start + len -1]); } } }return dp[0][n -1]; }
填左下一半的dp。
publicintlongestPalindromeSubseq(String s) {if (s ==null||s.length() ==0) {return0; }int n =s.length();int[][] dp =newint[n][n];for (int i =0; i < n; i++) { dp[i][i] =1; }for (int i =1; i < n; i++) {for (int j = i -1; j >=0; 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[n -1][0];}