华为笔试——查找两个字符串a,b中的最长公共子串

描述

查找两个字符串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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值