问题描述:假设有两个字符,要求检查两个字符串的重叠部分并进行拼接。例如abcdefg和fghik拼接得到abcdefghik,1234和23456拼接得到123456,而1234和678无法拼接。
参考代码:
def checkAndMerge(s1, s2):
m = min(len(s1), len(s2))
for i in range(m, 0, -1):
# 比较s1的最后i个字符是否与s2的前i个字符一样
if s1[-i:]==s2[:i]:
return s1+s2[i:]
print(checkAndMerge('abcdefg', 'fghik'))
print(checkAndMerge('1234', '23456'))
print(checkAndMerge('abcdefg', 'abcdefghijkl'))
print(checkAndMerge('abcdefg', 'bcdefghijkl'))
print(checkAndMerge('abcdef', 'abcdefghijkl'))
运行结果:
abcdefghik
123456
abcdefghijkl
abcdefghijkl
abcdefghijkl