返回序列,则加上公共字符串,否则计数

状态转移

如果s1[i] == s2[j]
那么状态转移方程就为 dp[i][j] = dp[i-1][j-1] + s1[i-1]
否则就为i-1 和j - 1 中的长度最大值

if len(dp[i-1][j]) > len(dp[i][j-1]):
    dp[i][j] = dp[i-1][j]
else:
    dp[i][j] = dp[i][j-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)
        dp = [['' for _ in range(l2+1)] for _ in range(l1+1)]
        for i in range(1, l1 + 1):
            for j in range(1, l2 + 1):
                if s1[i - 1] == s2[j - 1]:
                    dp[i][j] = dp[i-1][j-1] + s1[i-1]
                else:
                    if len(dp[i-1][j]) > len(dp[i][j-1]):
                        dp[i][j] = dp[i-1][j]
                    else:
                        dp[i][j] = dp[i][j-1]
        if dp[l1][l2] == '':
            return -1
        else:
            return dp[l1][l2]