动态规划——516. Longest Palindromic Subsequence[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".


注意子串和子序列的区别,子串是连续的,子序列要按顺序但不一定连续。本题要找最长的回文子序列。


解题思路

1)数组result[i][j]表示字符串i~j之间的最长回文子序列。

2)判断str[i]== str[j],是的话,result[i][j] = result[i+1][j-1]+2,不然

result[i][j]= max(result[i+1][j],result[i][j-1])

3)返回result[0][str。size()-1]


注意:

1)因为result[i][j]可能等于result[i+1][j-1],所以,i+1必须在 i 之前算出来,j-1必须在 j 之前算出来。因此 i 逆序遍历,j 顺序

2)这是动态规划算法,result[i][j]要依赖于之前的结果,所以str[i]== str[j]时,不能简单的result[i][j]++,要

result[i][j] = result[i+1][j-1]+2


代码如下


class Solution {
public:
    int longestPalindromeSubseq(string s) {
	vector<int> tmp(s.size(), 0);
	vector<vector<int> > result(s.size(), tmp);

	for (int i = 0; i < s.size(); i++)
		result[i][i] = 1;

	for (int i = s.size()-1; i >= 0; i--){
		for (int j = i + 1; j < s.size(); j++) {
			if (s[i] == s[j]) {
					result[i][j] = result[i + 1][j - 1] + 2;
			}
			else {
				result[i][j] = fmax(result[i][j - 1], result[i + 1][j]);
			}
		}
	}

	return result[0][s.size() - 1];
}

};


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值