程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python 最長公共子序列 LCS LCSS

編輯:Python
def init(arr, n, m):
for i in range(n):
temp = [0] * m
arr.append(temp)
def LCS(a, b, n, m):
dp = []
h = []
init(dp, n, m)
init(h, n, m)
for i in range(1, n):
for j in range(1, m):
if a[i - 1] == b[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
h[i][j] = 0
else:
if dp[i][j - 1] >= dp[i - 1][j]:
dp[i][j] = dp[i][j - 1]
h[i][j] = 1
else:
dp[i][j] = dp[i - 1][j]
h[i][j] = 2
return dp, h
def LCSS(h, a, n, m):
i = n - 1
j = m - 1
res = ""
while i > 0 and j > 0:
if h[i][j] == 0:
res = a[i - 1] + res
i -= 1
j -= 1
elif h[i][j] == 1:
j -= 1
elif h[i][j] == 2:
i -= 1
return res
a = "abcbdacb"
b = "bdcab"
n = len(a) + 1
m = len(b) + 1
dp, h = LCS(a, b, n, m)
res = LCSS(h, a, n, m)
print(res)


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved