2019年11月9日 星期六

Longest Palindromic Subsequence


Longest Palindromic Subsequence

  • Lintcode : 667 / Leetcode : 516
  • Level : Medium

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
Example1

Input: "bbbab"
Output: 4
Explanation:
One possible longest palindromic subsequence is "bbbb".
Example2

Input: "bbbbb"
Output: 5

Concept & Algorithm

Time Complexity & Space Complexity

time : O(n ^ 2)
space: O(n ^ 2)

Answer

class Solution {
public:
    int longestPalindromeSubseq(string &s) {
        int len = s.size();
        if (len == 0) return 0;
        vector<vector<int>> dp(len, vector<int>(len, 0));
        for (int i = 0; i < len; i++) {
            dp[i][i] = 1;
            for (int j = i - 1; j >= 0; j--) {
                if (s[i] == s[j]) {
                    dp[j][i] = dp[j + 1][i - 1] + 2;
                }else {
                    dp[j][i] = max(dp[j + 1][i], dp[j][ i - 1]);
                }
            }
        }
        return dp[0][len - 1];
    }
};
tags: DP

沒有留言:

張貼留言

Last Position of Target

Last Position of Target Lintcode : 458 / Leetcode : 34 Level : Easy Problem Find the last position of a target number in a sorted ...