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

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

http://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506

while True:
try:
s1 = input()
s2 = input()
if len(s1) > len(s2):
s2,s1 = s1,s2#让s1的字符串较短
max = [0,''] #存放找到的最大子串
lenth = 1 #为截取字符串的长度
for x in range(len(s1)+1): #lenth最多自增到s1的长度,每次循环lenth自增1
for i in range(len(s1)-lenth): #循环截取s1,在s2中寻找是否有匹配
if s1[i:i+lenth+1] in s2: #如若在s2中找到
max = [lenth,s1[i:i+lenth+1]] #存入max中
break
if max[0] != lenth: #如果lenth长度的子串不存在,必定lenth+1的子串也不存在
break #直接停止找寻子串
lenth += 1
print(max[1])
except:
break

全部评论

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务