Program to find length of longest palindromic subsequence in Python

PythonServer Side ProgrammingProgramming

Suppose we have a lowercase string s; we have to find the length of the longest palindromic subsequence in s.

So, if the input is like s = "aolpeuvekyl", then the output will be 5, as the palindrome is "level".

To solve this, we will follow these steps −

  • n := size of s
  • Define a function dp() . This will take i, j
  • if i is same as j, then
    • return 1
  • otherwise when i > j, then
    • return 0
  • otherwise,
    • if s[i] is same as s[j], then
      • return 2 + dp(i + 1, j - 1)
    • otherwise,
      • return maximum of dp(i + 1, j) and dp(i, j - 1)
  • return dp(0, n - 1)

Example (Python)

Let us see the following implementation to get better understanding −

 Live Demo

class Solution:
   def solve(self, s):
      n = len(s)
      def dp(i, j):
         if i == j:
            return 1
         elif i > j:
            return 0
         else:
            if s[i] == s[j]:
               return 2 + dp(i + 1, j - 1)
            else:
               return max(dp(i + 1, j), dp(i, j - 1))
      return dp(0, n - 1)
ob = Solution()
s = "aolpeuvekyl"
print(ob.solve(s))

Input

"aolpeuvekyl"

Output

5
raja
Published on 12-Dec-2020 15:15:08
Advertisements