imashutosh51

Longest Palindromic Subsequence

Mar 7th, 2026
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.01 KB | None | 0 0
  1. '''
  2. LCS variation: Here you have to find the LCS in the string s1 that is for sure and palidrome is something same as right to left so reversing the string and finding LCS between s1 and reversed(s1) will give you an LCS and that exist in the origing string also because LCS property is to match the order so it is for sure, you have picked the valid LCS of the string, now you have found LCS with reversed of the string so the LCS you have got is gonna be palindrom too. so
  3. find LCS between s and reversed(1) and that will be the palindrome LCS.
  4. '''
  5. def fun(s1,s2,n,m,dp):
  6.     if n<0 or m<0:
  7.         return 0
  8.     if dp[n][m]!=-1:
  9.         return dp[n][m]
  10.     if s1[n]==s2[m]:
  11.         dp[n][m]=1+fun(s1,s2,n-1,m-1,dp)
  12.     else:
  13.         dp[n][m]=max(fun(s1,s2,n-1,m,dp), fun(s1,s2,n,m-1,dp))
  14.     return dp[n][m]
  15. class Solution:
  16.     def longestPalindromeSubseq(self, s: str) -> int:
  17.         dp=[[-1]*len(s) for _ in range(len(s))]
  18.         s2=''.join(reversed(s))
  19.         return fun(s,s2,len(s)-1,len(s)-1,dp)
  20.        
Advertisement
Add Comment
Please, Sign In to add comment