Leetcode 516 Longest Palindromic Subsequence

来源:互联网 发布:80岁 编程 编辑:程序博客网 时间:2024/06/07 22:37

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的问题,在第i个和第j个char组成的部分里面,可以组成回文序列的长度取决于下面的子序列和当前ij这俩字符

如果相等 那么在i+1 j-1的基础上+2

如果不相等 那么 不能+2 只能取i j-1 或者 i+1 j的最大值

public 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] = dp[i+1][j-1] + 2;                }else{                    dp[i][j] = Math.max(dp[i][j-1], dp[i+1][j]);                }            }        }         return dp[0][s.length()-1];            }}

原创粉丝点击