zoukankan      html  css  js  c++  java
  • LCS 最长公共子子串

    与 最长公共子序列类似

    只是最长公共子串必须连续 所以只能走斜线!!!!

     1 '''
     2 LCS 最长公共子序列
     3 '''
     4 
     5 
     6 def LCS_len(x, y):
     7     m = len(x)
     8     n = len(y)
     9     dp = [[0] * (n + 1) for i in range(m + 1)]
    10     B = [[' '] * (n + 1) for i in range(m + 1)]
    11     for i in range(1, m + 1):
    12         for j in range(1, n + 1):
    13             if x[i - 1] == y[j - 1]:
    14                 dp[i][j] = dp[i - 1][j - 1] + 1
    15                 B[i][j] = 'X'
    16          
    17    
    18     return dp, B
    19 
    20 
    21 def LCS_str(B, x, i, j):
    22     if i == 0 or j == 0:
    23         return
    24     if B[i][j] == 'X':
    25         print(x[i - 1])
    26         LCS_str(B, x, i - 1, j - 1)
    27 
    28     # elif B[i][j] == 'L':
    29     #     LCS_str(B, x, i - 1, j)
    30     else:
    31         
    32         LCS_str(B, x, i, j - 1)
    33 
    34 
    35 
    36 def main():
    37     x = 'bab'
    38     y = 'caba'
    39     dp, B = LCS_len(x, y)
    40     LCS_str(B, x, len(x), len(y))
    41 main()
  • 相关阅读:
    Linq&Lumbda
    PS颜色模式
    WPF绑定方式
    明三杰刘健
    齐有鲍叔,郑有子皮
    朱厚照
    管子&小白
    时间
    人外有人之神箭手养繇基篇
    楚共王
  • 原文地址:https://www.cnblogs.com/zle1992/p/8871741.html
Copyright © 2011-2022 走看看