题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
while True: try: s1 = input() s2 = input() m = len(s1) n = len(s2) # 将短边设为行,纵向排列 if m > n: s1, s2 = s2, s1 m, n = n, m dp = [[0 for _ in range(n+1)] for _ in range(m+1)] max_length = 0 mark = -1 # 最外层循环先遍历短边 for i in range(1, m+1): for j in range(1, n+1): if s1[i-1] == s2[j-1]: dp[i][j] = dp[i-1][j-1] + 1 if dp[i][j] > max_length: max_length = dp[i][j] # 将当前最长公共子串在短边中的结束位置记录下来 mark = i print(s1[mark-max_length: mark]) except: break