题解 | #最长公共子序列(二)#

最长公共子序列(二)

https://www.nowcoder.com/practice/6d29638c85bb4ffd80c020fe244baf11

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# longest common subsequence
# @param s1 string字符串 the string
# @param s2 string字符串 the string
# @return string字符串
#
class Solution:
    def LCS(self , s1: str, s2: str) -> str:
        c = [[0 for _ in range(len(s1) + 1)] for _ in range(len(s2) + 1)]
        # 取元素时候外面的在前,比如c[i][j]
        # 这里增广一圈,方便计算
        for i in range(len(s2)):
            for j in range(len(s1)):
                if s2[i] == s1[j]:
                    c[i+1][j+1] = c[i][j] + 1
                else:
                    c[i+1][j+1] = max(c[i][j+1],c[i+1][j])
        if c[-1][-1] == 0:
            return '-1'
        i = len(s2) - 1
        j = len(s1) - 1
        s = ''
        while True:
            if c[i+1][j+1] == c[i][j+1]:
                i -= 1
            elif c[i+1][j+1] == c[i+1][j]:
                j -= 1
            else:
                s = s2[i] + s
                i -= 1
                j -= 1            
            if c[i+1][j+1] == 0:
                break
        return s

全部评论

相关推荐

牛客66512506...:那个百度acg是不是个小哥啊,老是问些底层问题狠狠为难,然后kpi
哪些公司在招寒假实习?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务