描述
查找两个字符串a,b中的最长公共子串。若有多个,输出在较短串中最先出现的那个。
注:子串的定义:将一个字符串删去前缀和后缀(也可以不删)形成的字符串。请和“子序列”的概念分开!
数据范围:字符串长度1≤𝑙𝑒𝑛𝑔𝑡ℎ≤300 1≤length≤300
进阶:时间复杂度:𝑂(𝑛3) O(n3) ,空间复杂度:𝑂(𝑛) O(n)
输入描述:
输入两个字符串
输出描述:
返回重复出现的字符
示例1
输入:
abcdefghijklmnop abcsafjklmnopqrstuvw
输出:
jklmnop
本题需要注意的是要按照两个字符串长短情况分类讨论,两种情况是相反的,可以在另一个解法的基础上调换两个字符串变量名的位置。
另外,需要设置两个变量分别指向当前比较的子串开始的索引位置,不可以直接用遍历体中的计数变量。可以采用遍历比较字符串结果列表中的长度,获取第一个与最大长度相等的字符串即为所求答案。
string1=input()
string2=input()
strlst=[]
if len(string1)<=len(string2):
for i in range(len(string1)):
for j in range(len(string2)):
nowindex=i
nowindex2=j
commonstr=''
flag=0
while nowindex<len(string1) and nowindex2<len(string2) and string2[nowindex2]==string1[nowindex]:
flag=1
commonstr+=string1[nowindex]
nowindex+=1
nowindex2+=1
if flag==1:
strlst.append(commonstr)
else:
continue
else:
for i in range(len(string2)):
for j in range(len(string1)):
nowindex=i
nowindex2=j
commonstr=''
flag=0
while nowindex<len(string2) and nowindex2<len(string1) and string1[nowindex2]==string2[nowindex]:
flag=1
commonstr+=string2[nowindex]
nowindex+=1
nowindex2+=1
if flag==1:
strlst.append(commonstr)
else:
continue
lengthlst=[len(string) for string in strlst]
maxlength=max(lengthlst)
for string in strlst:
if len(string)==maxlength:
print(string)
break