week7- Dynamic Programming-NO.516. Longest Palindromic Subsequence

来源:互联网 发布:里见浩太朗 知乎 编辑:程序博客网 时间:2024/06/05 15:42

题目

  • Total Accepted: 6936
  • Total Submissions: 16445
  • Difficulty: Medium
  • Contributors:Stomach_ache

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".
https://leetcode.com/problems/longest-palindromic-subsequence/#/description

思路

题目需要字符串s中最长的回文子串。

使用动态规划的思想,设l[i][j]表示字符串s中下标i到j的子串中的最长回文串,若子串的两边各增加一个字符,求l[i-1][j+1]时,若s[i-1]=sj[j+1],则找到了一个更长的回文,长度为l[i][j]+2,反之,子串中最长的回文串是l[i][j+1]和l[i-1][j]中的最大值。

源程序

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


0 0
原创粉丝点击