题目描述
给定两个字符串str1和str2,输出连个字符串的最长公共子序列。如过最长公共子序列为空,则输出-1。
# longest common subsequence
# @param s1 string字符串 the string
# @param s2 string字符串 the string
# @return string字符串
#
class Solution:
def LCS(self , s1 , s2 ):
# write code here
L1 ,L2 = len(s1) , len(s2)
if L1 == 0 or L2 == 0:
return -1
list = [[0]*(L1+1) for i in range(0,L2+1)]
for i in range(0,L2):
for j in range(0,L1):
if s1[j] == s2[i]:
list[i+1][j+1] = list[i][j] + 1
else:
list[i+1][j+1] = max(list[i][j+1],list[i+1][j])
if list[L2][L1] == 0:
return -1
j , i = L1 , L2
str = ''
while(i > 0 and j > 0):
if s1[j-1] == s2[i-1]:
str += s1[j-1]
i -= 1
j -=1
elif list[i][j-1] < list[i-1][j] :
i -=1
else:
j -=1
return (str[::-1])