Longest Palindromic Subsequence

https://leetcode.com/problems/longest-palindromic-subsequence/description/

Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000.

Thoughts

数组找长度想DP。刚开始还想是不是用背包做,发现做不出来。实际上沿着回文一般解法即可,让f[j][i]表示从j到i最长回文长度,对每个j, i判断是否相等,相等意味着保留ij能构成新的回文,旧长度+2。不等则意味着j和i不能共存, 可以是从j到i-1最长回文长度或者j + 1到i的。

Code

class Solution {
    public int longestPalindromeSubseq(String s) {
        int n = s.length();
        int[][] f = new int[n][n];


        for (int i = 0; i < n; i++) {
            f[i][i] = 1;
            for (int j = i - 1; j >= 0; j--) {
                if (s.charAt(i) == s.charAt(j)) {
                    f[j][i] = f[j + 1][i - 1] + 2;
                } else {
                    f[j][i] = Math.max(f[j][i - 1], f[j + 1][i]);
                }
            }
        }


        return f[0][n - 1];
    }
}

Analysis

时间复杂度为O(n^2).

Last updated