
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find length of longest palindromic subsequence in Python
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)
- if s[i] is same as s[j], then
- return dp(0, n - 1)
Example (Python)
Let us see the following implementation to get better understanding −
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
- Related Articles
- Program to find out the length of longest palindromic subsequence using Python
- Program to find length of longest palindromic substring in Python
- Program to find length of longest balanced subsequence in Python
- Program to find length of longest anagram subsequence in Python
- Program to find length of longest increasing subsequence in Python
- Program to find length of longest fibonacci subsequence in Python
- Longest Palindromic Subsequence
- Java Program for Longest Palindromic Subsequence
- Program to find length of longest circular increasing subsequence in python
- Longest Palindromic Subsequence in C++
- Program to find length of longest palindromic substring after single rotation in Python
- Program to find length of longest common subsequence of three strings in Python
- Program to find length of longest bitonic subsequence in C++
- Program to find length of longest common subsequence in C++
- Program to find length of longest arithmetic subsequence with constant difference in Python

Advertisements