最长公共子串

146 阅读1分钟

1. 题目

  • 最长公共子串(Longest Common Substring): 是指两个字符串中最长连续相同的子串长度。
  • 例如:str1=“1AB2345CD”,str2=”12345EF”,则str1,str2的最长公共子串为2345。

2. 核心代码

def find_lcsubstr(s1, s2):
    l1 = len(s1)
    l2 = len(s2)
    dp = [[0] * (l2 + 1) for _ in range(l1 + 1)]
    dp_max_str = 0
    p = 0
    for i in range(l1):
        for j in range(l2):
            if s1[i] == s2[j]:
                dp[i + 1][j + 1] = dp[i][j] + 1
                if dp[i + 1][j + 1] > dp_max_str:
                    dp_max_str = dp[i + 1][j + 1]
                    p = i + 1
    return s1[p - dp_max_str:p], dp_max_str  # 返回最长子串及其长度


print(find_lcsubstr('bcdabcdjal', 'abcd'))