https://www.youtube.com/watch?v=_nCsPn7_OgI
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: DP
思路:
DP definition : maintain dp[i][j] table, which keep tracking of the longest palindrome length inside s[i , j]
Initialization : dp[i][i] = 1, i.e. each single character count as 1
Transfer equation :
- 循环式:
for(int l = 2; l <= str.length; l++)
for(int i = 0; i < str.length-l + 1; i++)
let j = i + l - 1
- if (s[i] ==s[j] && l == 2)
dp[i, j] = 2
- else if (s[i] == s[j])
dp[i, j] = 2 + dp[i +i, j -1]
- else
dp[i, j] = max(dp[i, j -1], dp[i + 1, j])
Output : dp[0][n-1]