题解 | #查找两个字符串a,b中的最长公共子串#

查找两个字符串a,b中的最长公共子串

https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506?tpId=37&tqId=21288&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3Fdifficulty%3D3%26page%3D1%26pageSize%3D50%26search%3D%26tpId%3D37%26type%3D37&difficulty=3&judgeStatus=undefined&tags=&title=

  • 状态转移方程
  • a[i] == b[i], dp[i][j] = dp[i-1][j-1],dp表示以a[i]结尾的字串和以b[j]结尾的字串的最长公共子串
a = input()
b = input()

# 确保a就是较短串
if len(a) > len(b):
    a, b = b, a

# 初始化
n, m = len(a) + 1, len(b) + 1
dp = [[0] * m for _ in range(n)]

max_n = 0
idx = -1
for i in range(1, n, 1):
    for j in range(1, m, 1):
        if a[i-1] == b[j-1]:
            dp[i][j] = dp[i - 1][j - 1] + 1
        if dp[i][j] > max_n:
            max_n = dp[i][j]
            # dp[i][j]表示的是下标为i-1,j-1的两个字串
            idx = i-1

print(a[idx - max_n + 1 : idx + 1] if idx != -1 else "")

全部评论

相关推荐

在做测评的伊登很想奋...:别看了,简历没问题,中国人才太多了,所以显得没什么光辉,别怀疑,这水平进不去,那证明企业里边全是985。除了多投碰运气也没啥办法。
点赞 评论 收藏
分享
10-13 13:49
南京大学 财务
饿魔:笑死我了,你简直是个天才
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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