leetcode 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:
Input:

"bbbab"
Output:
4
One possible longest palindromic subsequence is "bbbb".
Example 2:
Input:

"cbbd"
Output:
2
One possible longest palindromic subsequence is "bb".

分析过程

  • 题目归类:
    动态规划
  • 题目分析:
    因为是子序列,所以需要判断两种情况,一种是两边相等,中间数据和两边不等。
  • 边界分析:
    • 空值分析
    • 循环边界分析
  • 方法分析:
    • 数据结构分析
    • 状态机
    • 状态转移方程
    • 最优解
  • 测试用例构建

代码实现

class Solution {
    public int longestPalindromeSubseq(String s) {
        if(s==null)
            return 0;
        int n = s.length();
        int dp[][] = new int[n][n];
        for(int i = n-1; i >= 0;i--){
            for(int j = i; j < n ; j++){
                if(i==j)
                    dp[i][j] = 1;
                else if(j-i==2){
                    if(s.charAt(i)==s.charAt(j))
                        dp[i][j] = 3; 
                    else if(s.charAt(i)==s.charAt(i+1)||s.charAt(j)==s.charAt(j-1)){
                        dp[i][j] = 2;
                    }
                    else
                        dp[i][j] = 1;
                    
                        
                }
                else if(j-i==1){
                    if(s.charAt(i)==s.charAt(j))
                        dp[i][j] = 2; 
                    else
                        dp[i][j] = 1;
                }
                else {
                    int tmp = Math.max(dp[i+1][j],dp[i][j-1]);
                    int tmp1 = s.charAt(i)==s.charAt(j)?2+dp[i+1][j-1]:dp[i+1][j-1];
                    dp[i][j] = Math.max(tmp,tmp1);
                }    
            }
        }
        return dp[0][n-1];
    }
}

效率提高

拓展问题

  1. Palindromic Substrings

猜你喜欢

转载自www.cnblogs.com/clnsx/p/12287680.html
今日推荐