Longest Palindromic Subsequence
Description:
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
Given s = “bbbab” return 4
One possible longest palindromic subsequence is “bbbb”.
Code:
class Solution:
"""
@param s: the maximum length of s is 1000
@return: the longest palindromic subsequence's length
"""
def longestPalindromeSubseq(self, s):
# write your code here
if not s:
return 0
ls = len(s)
dp = [[0 for _ in range(ls)] for _ in range(ls)]
for i in range(ls):
dp[i][i] = 1
for j in range(i-1, -1, -1):
if s[i]==s[j]:
dp[i][j] = dp[i-1][j+1] + 2
else:
dp[i][j] = max(dp[i-1][j], dp[i][j+1])
return dp[ls-1][0]