题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
a = raw_input()
b = raw_input()
这个是我参考别人的,在他的基础上修复了字符串为1的情况不打印结果的bug,增加了两个字符串长度相同时,输出两个字符串里面更靠前的公共子串。
def f(a,b):
if len(a)>len(b):
a,b=b,a
res = ''
for i in range(0,len(a)+1):
for j in range(i,len(a)):
if a[i:j+1] in b and j+1-i>len(res):
res = a[i:j+1]
ml = len(res)
ls = {}
if len(a) == len(b):
b = raw_input()
这个是我参考别人的,在他的基础上修复了字符串为1的情况不打印结果的bug,增加了两个字符串长度相同时,输出两个字符串里面更靠前的公共子串。
def f(a,b):
if len(a)>len(b):
a,b=b,a
res = ''
for i in range(0,len(a)+1):
for j in range(i,len(a)):
if a[i:j+1] in b and j+1-i>len(res):
res = a[i:j+1]
ml = len(res)
ls = {}
if len(a) == len(b):
#下来利用公共子串在字符串出现的位置作为字典的key,公共子串作为value来实现
for i in range(len(a)):
if a[i:i+ml] in b and i+ml <len(a)+1:
ls[i] = a[i:i+ml]
for j in range(len(b)):
if b[j:j+ml] in a and j+ml <len(b)+1:
ls[j] = b[j:j+ml]
ls2 = sorted(ls.keys())
print ls[0]
else:
print res
f(a, b)
for i in range(len(a)):
if a[i:i+ml] in b and i+ml <len(a)+1:
ls[i] = a[i:i+ml]
for j in range(len(b)):
if b[j:j+ml] in a and j+ml <len(b)+1:
ls[j] = b[j:j+ml]
ls2 = sorted(ls.keys())
print ls[0]
else:
print res
f(a, b)