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 −
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))
"aolpeuvekyl"
5