516. Longest Palindromic Subsequence

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".

本题应该使用DP的方法来做,先考虑DP是需要用数组来保存数据还是一个整型来保存数据,注意本题的特点,本题是考察回文,因此需要左端点和右端点,因此需要用到二维数组来解决问题。然后考虑状态方程,考虑到:if(charAt(i)==charAt(j)) dp[i][j] = dp[i+1][j-1]+2;如果不相等,则取比他范围小的回文最大子字符串,即:dp[i][j] = Math.max(dp[i+1][j],dp[i][j-1]);最后考虑初值情况,本题初值是dp[i][i] = 1;可以作为已知,代码如下:

 1 public class Solution {
 2     public int longestPalindromeSubseq(String s) {
 3         int[][] dp = new int[s.length()][s.length()];
 4         for(int i=0;i<s.length();i++){
 5             dp[i][i] = 1;
 6             for(int j=i-1;j>=0;j--){
 7                 if(s.charAt(i)==s.charAt(j)){
 8                     dp[j][i] = dp[j+1][i-1]+2;
 9                 }else{
10                     dp[j][i] = Math.max(dp[j][i-1],dp[j+1][i]);
11                 }
12             }
13         }
14         return dp[0][s.length()-1];
15     }
16 }

DP还可以使用自顶向下来做,代码如下:

 1 public class Solution {
 2     public int longestPalindromeSubseq(String s) {
 3         return helper(s,0,s.length()-1,new Integer[s.length()][s.length()]);
 4     }
 5     public int helper(String s,int start,int end,Integer[][] dp){
 6         if(dp[start][end]!=null) return dp[start][end]; 
 7         if(start>end) return 0;
 8         if(start==end) return 1;
 9         if(s.charAt(start)==s.charAt(end)){
10             dp[start][end] = helper(s,start+1,end-1,dp)+2;
11         }else{
12             dp[start][end] = Math.max(helper(s,start+1,end,dp),helper(s,start,end-1,dp));
13         }
14         return dp[start][end];
15     }
16 }

 

posted @ 2017-03-22 02:58  CodesKiller  阅读(203)  评论(0编辑  收藏  举报