Longest Palindromic Subsequence

Problem

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

Solution

Recursive Solution using Two Pointers

public class Solution {
    public int longestPalindromeSubseq(String s) {
        if (s == null || s.length() == 0) return 0;
        return helper(s, 0, s.length() - 1);
    }

    private int helper(String s, int start, int end) {
        if (start == end) return 1;
        if (start > end) return 0;
        return s.charAt(start) == s.charAt(end) ? 2 + helper(s, start + 1, end - 1) : Math.max(helper(s, start + 1, end), helper(s, start, end - 1));
    }
}

DP Solution with same idea above

public class Solution {
    public int longestPalindromeSubseq(String s) {
        if (s == null || s.length() == 0) return 0;
        int len = s.length();
        int[][] dp = new int[len][len];
        for (int i = len - 1; i >= 0; i--) {
            dp[i][i] = 1;
            for (int j = i + 1; j < len; 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][j - 1], dp[i + 1][j]);
            }
        }
        return dp[0][len - 1];
    }
}

Analysis

The idea of this problem is to use two pointers from left and right and compare the character
If s.charAt(left) == s.charAt(right), we shrink the interval and increment the result by 2
In the recursive solution, we use recursion to accomplish this
However, it's costly hence we use dp to improve it

dp[i][j] is the longest palindromic subsequence with substring i, j both inclusive
The transition state is dp[i][j] = 2 + dp[i + 1][j - 1] if s.charAt(i) == s.charAt(j)
Otherwise, dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1])
Notice that we update [i] with [i + 1] Hence we need to do this dp from the end to start to make sure [i + 1] is always there And to make sure j - 1 is already there, we init j = i + 1

results matching ""

    No results matching ""