python 最长公共子序列

记录一下,因为看到很多python版本生成最长公共子序列都用的递归,这里只返回一个符合条件的最长公共子序列

class Solution:
    def LCS(self,s1,s2):
        c = len(s1)+1
        r = len(s2)+1
        dp = [[0]*c for i in range(r)]
        for i in range(1,r):
            for j in range(1,c):
                if s1[j-1] == s2[i-1]:
                    dp[i][j] = dp[i-1][j-1]+1
                else:
                    dp[i][j] = max(dp[i-1][j],dp[i][j-1])
        maxl = dp[-1][-1]
        print(maxl)
        # 生成最长公共子序列,只返回满足条件的一个
        res = []
        i = r-1
        j = c-1
        while i > 0 and j > 0:
            if s1[j-1] == s2[i-1]:
                res.append(s1[j-1])
                i -= 1
                j -= 1
            else:
                if dp[i-1][j] > dp[i][j-1]:
                    i -= 1
                else:
                    j -= 1
        return ''.join(res[::-1])

if __name__ == '__main__':
    p = Solution()
    a = input('enter s1:')
    while a != 'e':
        b = input('enter s2:')
        print(p.LCS(a,b))
        a = input('enter s1:')

猜你喜欢

转载自blog.csdn.net/jingjing_94/article/details/80539403