516. Longest Palindromic Subsequence
Medium
Input: s = "bbbab"
Output: 4
Explanation: One possible longest palindromic subsequence is "bbbb".Input: s = "cbbd"
Output: 2
Explanation: One possible longest palindromic subsequence is "bb".class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
rev = s[::-1]
dp = [[0]*(len(s)+1) for _ in range(len(s)+1)]
length = len(s)
for i in range(1, length+1):
for j in range(1, length+1):
if s[i-1] == rev[j-1]:
dp[i][j] = dp[i-1][j-1]+1
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
return dp[length][length]Last updated