LeetCode 516. Longest Palindromic Subsequence
题目描述:
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:
1
2 "bbbab"Output:
1
2 4One possible longest palindromic subsequence is “bbbb”.
Example 2: Input:
1
2 "cbbd"Output:
1
2 2One possible longest palindromic subsequence is “bb”.
二维DP。dp[i][j]
表示s[i]
到s[j]
(含两端)的字符串中最长的回文子串。状态转移方程如下:
i==j
,dp[i][j]=1
s[i]==s[j-1]
,dp[i][j]=2
s[i]==s[j]
,dp[i][j]=dp[i+1][j-1]+2
s[i]!=s[j]
,dp[i][j]=max(dp[i+1][j], dp[i][j-1])
1 | class Solution { |