题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
http://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
#使用动态规划取得记录最长连续子串的二维数组,再从二维数组中获取需要的子串在原字符串中的位置
try:
c=input()
d=input()
except:
break
else:
if len(c) > len(d):
a = d
b = c
else:
a = c
b = d
len_a = len(a)+1
len_b = len(b)+1
dp = [[0 for i in range(len(a) + 1)] for j in range(len(b) + 1)]
for j in range(1,len_b):
for i in range(1,len_a):
if a[i-1] == b[j-1]:
dp[j][i] = dp[j-1][i-1] + 1
else:
dp[j][i] = 0
maxx=0
maxx_str = ''
indexx = ()
for i in range(1,len_a):
for j in range(1,len_b):
if dp[j][i] >maxx:
maxx = dp[j][i]
maxx_str = "".join(a[dp[j].index(maxx)-maxx:dp[j].index(maxx)])
indexx = (dp[j].index(maxx)-maxx,dp[j].index(maxx))
# print(dp)
# print(a,indexx)
print(maxx_str)