最长公共子串
查找两个字符串a,b中的最长公共子串
https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
s1=input()
s2=input()
''' # 先识别字符串长短,再求公共子串,找最长字串
# 报红:运行超时
for s in (s1,s2):
if len(s)==max(len(s1),len(s2)):
long=s
#print(long)
elif len(s)==min(len(s1),len(s2)):
short=s
#print(short)
# 识别公共子串可以简化,截取s1子串,若在s2中,则是公共子串,不用遍历s1、s2所有子串
short_l=[]
for i in range(len(short)):
for j in range(i+1,len(short)+1):
short_l.append(short[i:j])
#print(short_l)
long_l=[]
for i in range(len(long)):
for j in range(i+1,len(long)+1):
long_l.append(long[i:j])
#print(long_l)
common_l={}
for i in short_l:
for j in long_l:
if i==j:
common_l[i]=len(i)
#print(common_l)
'''
#设定s1为较短字符串,若不是,交换
if len(s1)>len(s2):
s1,s2=s2,s1
#截取s1子串,若在s2中,则是公共子串
#将公共子串存在common中,若有更长的公共子串,更新common,最终结果即为最长的一个
common=''
for i in range(len(s1)):
for j in range(i+1,len(s1)+1):
if s1[i:j] in s2 and j-i>len(common):
common=s1[i:j]
print(common)
#若有多个,输出在s1、s2较短串中最先出现的那个。
查看25道真题和解析
字节跳动公司福利 1301人发布