516. Longest Palindromic Subsequence(第十七周)

来源:互联网 发布:oracle 数据库备份 编辑:程序博客网 时间:2024/06/05 17:05

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


寻找最长的回文串,找到关键方程dp[i][j] = dp[i+1][j-1] + 2

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

原创粉丝点击