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: O(N^2)
字符串的问题的DP有的时候需要考虑2D的DP解法。这题就是一个列子。
假设dp[i][j]是指(i,j)的子字符串的LPS, 那么如果首尾字符相同的话
dp[i][j] = dp[i + 1][j - 1] + 2
如果不相同的话,可以是错位match,也就是说要么用上尾字符,要么用上头字符。
dp[i][j] = max(dp[i+1][j], dp[i][j-1])
C++
Java