动态规划——最长公共子序列与最长公共子串 (含Python实现代码)

时间:2020-07-08 15:13:41   收藏:0   阅读:78

动态规划——最长公共子序列与最长公共子串 (含Python实现代码)

最长公共子序列

\[ c[i][j] = \left\{ \begin{array}{} 0 & {i = 0, j = 0}\c[i-1][j-1] + 1 & {X_i = Y_j}\MAX(c[i-1][j], c[i][j-1]) & {X_i \neq Y_j}\\end{array} \right. \]

def longest_common_subsequence(X: str, Y: str):
    index_x = len(X)+1  # columns
    index_y = len(Y)+1  # rows
    c = [[‘‘]*index_y for _ in range(index_x)]

    for i in range(index_x):
        for j in range(index_y):
            if i == 0 or j == 0:
                c[i][j] = ‘‘
                continue
            if X[i-1] == Y[j-1]:
                c[i][j] = c[i-1][j-1] + X[i-1]
            else:
                if len(c[i-1][j]) > len(c[i][j-1]):
                    c[i][j] = c[i-1][j]
                else:
                    c[i][j] = c[i][j-1]

    return len(c[index_x-1][index_y-1]), c[index_x-1][index_y-1]

最长公共子串

方法差不多,有人看再更

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!