[LeetCode] Longest Palindromic Subsequence 最长回文子序列

来源:互联网 发布:知学学院宋剑勇 编辑:程序博客网 时间:2024/06/10 05:46

声明:原题目转载自LeetCode,解答部分为原创

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

Solution:

        思路:动态规划问题,假定f(left, right)为字符数组string[ left, right ]中存在的回文子序列的最大值。其状态转换方程为:

        if left > right, then f( left, right ) = 0,

        else if left = right, then f( left, rigth ) = 1

         else if s[ left ] = s[ right ], then f( left, right ) = f( left + 1, right - 1 ) + 2,

        else, f( left, right ) = max( f( left + 1, right ), f( left, right - 1) )

        代码如下:

#include<iostream>#include<vector>using namespace std;class Solution {public:    int longestPalindromeSubseq(string s) {        vector<vector<int> > length(s.size(), vector<int>(s.size()));                for(int i = s.size() - 1 ; i >= 0; i --)        {        length[i][i] = 1;        for(int k = 0 ; k < i ; k ++){length[i][k] = 0;}         for(int j = i + 1; j < s.size(); j ++)        {        if(s[i] == s[j])        length[i][j] = length[i + 1][j - 1] + 2;        else        length[i][j] = max(length[i + 1][j], length[i][j - 1]);}}return length[0][s.size() - 1];    }    /*    int length(string s, int i, int j)    {    if(i == j)    return 1;    else if(i > j)        return 0;    else if(s[i] == s[j])    return length(s, i + 1, j - 1) + 2;    else    return max(length(s, i + 1, j), length(s, i, j - 1));}*/};int main(){Solution text;cout << text.longestPalindromeSubseq("aabcda") << endl;  return 0;}



阅读全文
0 0