Longest Palindromic Subsequence

This commit is contained in:
Putul Singh 2024-10-19 15:06:54 +05:30 committed by GitHub
parent 8dcffa3e71
commit 81c09d1a3b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1,44 +1,53 @@
""" def longest_palindromic_subsequence(input_string: str) -> int:
author: Sanket Kittad """
Given a string s, find the longest palindromic subsequence's length in s. Function to find the length of the longest palindromic subsequence
Input: s = "bbbab" in a given string using dynamic programming.
Output: 4
Explanation: One possible longest palindromic subsequence is "bbbb". :param input_string: Input string
Leetcode link: https://leetcode.com/problems/longest-palindromic-subsequence/description/ :return: Length of the longest palindromic subsequence
"""
>>> longest_palindromic_subsequence("bbbab")
4
def longest_palindromic_subsequence(input_string: str) -> int: >>> longest_palindromic_subsequence("cbbd")
""" 2
This function returns the longest palindromic subsequence in a string >>> longest_palindromic_subsequence("")
>>> longest_palindromic_subsequence("bbbab") 0
4 >>> longest_palindromic_subsequence("a")
>>> longest_palindromic_subsequence("bbabcbcab") 1
7 >>> longest_palindromic_subsequence("abcd")
""" 1
n = len(input_string) >>> longest_palindromic_subsequence("agbdba")
rev = input_string[::-1] 5
m = len(rev) """
dp = [[-1] * (m + 1) for i in range(n + 1)] n = len(input_string)
for i in range(n + 1):
dp[i][0] = 0 # Base case: if string is empty, return 0
for i in range(m + 1): if n == 0:
dp[0][i] = 0 return 0
# create and initialise dp array # dp[i][j] will represent the length of the longest palindromic subsequence
for i in range(1, n + 1): # within the substring input_string[i...j]
for j in range(1, m + 1): dp = [[0] * n for _ in range(n)]
# If characters at i and j are the same
# include them in the palindromic subsequence # Every single character is a palindrome of length 1
if input_string[i - 1] == rev[j - 1]: for i in range(n):
dp[i][j] = 1 + dp[i - 1][j - 1] dp[i][i] = 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) # Build the DP table for substrings of increasing length
for length in range(2, n + 1):
return dp[n][m] for i in range(n - length + 1):
j = i + length - 1
if input_string[i] == input_string[j]:
if __name__ == "__main__": dp[i][j] = dp[i + 1][j - 1] + 2
import doctest else:
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])
doctest.testmod()
# The longest palindromic subsequence length for the full string is dp[0][n-1]
return dp[0][n - 1]
# Example usage:
if __name__ == "__main__":
input_string = "bbbab"
result = longest_palindromic_subsequence(input_string)
print(f"Length of Longest Palindromic Subsequence: {result}")