最长回文子序列的Python程序| DP-12
给定一个序列,找出其中最长的回文子序列的长度。
再举一个例子,如果给定的序列是“BBABCBCAB”,那么输出应该是 7,因为“BABCBAB”是其中最长的回文子序列。 “BBBBB”和“BBCBB”也是给定序列的回文子序列,但不是最长的。
1) 最优子结构:
令 X[0..n-1] 为长度为 n 的输入序列,L(0, n-1) 为 X[0..n-1] 的最长回文子序列的长度。
如果 X 的最后一个字符和第一个字符相同,则 L(0, n-1) = L(1, n-2) + 2。
否则 L(0, n-1) = MAX (L(1, n-1), L(0, n-2))。
以下是处理所有情况的通用递归解决方案。
动态规划解决方案
Python3
# A Dynamic Programming based Python
# program for LPS problem Returns the length
# of the longest palindromic subsequence in seq
def lps(str):
n = len(str)
# Create a table to store results of subproblems
L = [[0 for x in range(n)] for x in range(n)]
# Strings of length 1 are palindrome of length 1
for i in range(n):
L[i][i] = 1
# Build the table. Note that the lower
# diagonal values of table are
# useless and not filled in the process.
# The values are filled in a
# manner similar to Matrix Chain
# Multiplication DP solution (See
# https://www.geeksforgeeks.org/
# dynamic-programming-set-8-matrix-chain-multiplication/
# cl is length of substring
for cl in range(2, n + 1):
for i in range(n-cl + 1):
j = i + cl-1
if str[i] == str[j] and cl == 2:
L[i][j] = 2
elif str[i] == str[j]:
L[i][j] = L[i + 1][j-1] + 2
else:
L[i][j] = max(L[i][j-1], L[i + 1][j]);
return L[0][n-1]
# Driver program to test above functions
seq = "GEEKS FOR GEEKS"
n = len(seq)
print("The length of the LPS is " + str(lps(seq)))
# This code is contributed by Bhavya Jain
输出:
The length of the LPS is 7
时间复杂度:- O(n 2 )
请参阅有关最长回文子序列的完整文章 | DP-12 了解更多详情!