516. Longest-Palindromic-Subsequence

difficulty: Medium

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

Constraints:

  • 1 <= s.length <= 1000

  • s consists only of lowercase English letters.

Method One

class Solution {
    public int longestPalindromeSubseq(String s) {
        // 参见 1312
        int N = s.length();
        int[][] dp = new int[N + 1][ N + 1];
        for(int i = 0; i < N; i++ ) {
            for(int j = 0; j < N; j++ ) {
                int end = N - 1 - j;
                if( s.charAt(i) == s.charAt(end) ) {
                    dp[i + 1][j + 1] = dp[i][j] + 1;
                }else{
                    dp[i + 1][j + 1] = Math.max(dp[i][j + 1], dp[i + 1][j]);
                }
            }
        }
        return dp[N][N];
    }
} 

Last updated

Was this helpful?