516 Longest Palindromic Subsequence

178 篇文章 0 订阅
160 篇文章 0 订阅

1 题目

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

2 尝试解

2.1 分析

给定一个字符串,求其最长回文子序列(子序列不要求连续),与最长连续公共子序列动态递归思路相似。

longest-palindrome(s,i,j)

s[i]==s[j] : longest-palindrome(s,i,j) = 2 + longest-palindrome(s,i+1,j-1)

s[i]!=s[j] : longest-palindrome(s,i,j) = max(longest-palindrome(s,i+1,j),longest-palindrome(s,i,j-1))

或者直接将字符串翻转,求最长公共子序列。

2.2 代码

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

3 标准解

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值