题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
s = [] s.append(input()) s.append(input()) if len(s[0]) > len(s[1]): s1 = s[1] s2 = s[0] else: s1 = s[0] s2 = s[1] dp = [0 for _ in range(len(s1))] for i in range(len(s1)): for j in range(len(s2)): if s1[i] == s2[j]: l = 0 x, y = i, j while x >= 0 and y >= 0 and s1[x] == s2[y]: l += 1 x -= 1 y -= 1 dp[i] = max(dp[i], l) max_len = 0 max_i = 0 for i in range(len(dp)): if dp[i] > max_len: max_len = dp[i] max_i = i print(s1[max_i - max_len + 1 : max_i + 1])