给出2个字符串,输出2字符串的最长公共子串。
输入格式:
输入2个字符串,不可包含空格。
输出格式:
输出2个字符串的最长公共子串。若没有公共子串,则输出“NULL”
输入样例1:
abcding
sbcdiofng
结尾无空行
输出样例1:
bcdi
结尾无空行
输入样例2:
understanding
fw
输出样例2:
NULL
a = input()
b = input()
def maxSubstring(a,b):
if a==None or b==None:#空值返回
return None
#接下来获取两者较长和较短的字符串
if len(a)>len(b):
M=a
m=b
else:
M=b
m=a
#遍历遍历较短的字符串,并依次减少短字符串的字符数量,
#判断长字符是否包含该子串
i=0
while i<len(m):
begin=0
end=len(m)-i
#先扣住end部分的字符,然后一个循环看begin从0~end是否有符合的最大串
while end<=len(m):
current=m[begin:end]
if current in M:
return current
begin+=1
end+=1
i+=1
return 'NULL'
print(maxSubstring(a,b))
摘自求最大公共子字符串题解太妙了