s1 = 'abcdefg'
s2 = 'defabcdoabcdeftw'
s3 = '1234a'
s4 = 'wqweshjkb'
s5 = 'defabcd'
s6 = 'j'
求 s1、s3、s4、s5、s6 分别与 s2 的最长共同子串,分别测试有共同子串和没有共同子串的情况下此函数效率问题。
s1 = 'abcdefg'
s2 = 'defabcdoabcdeftw'
s3 = '1234a'
s4 = 'wqweshjkb'
s5 = 'defabcd'
s6 = 'j'
def findstr(str1,str2):
'''
Returns str1 and str2 longest common substring. 2017/10/21 23:30
:param str1: 'abcdefg'
:param str2: 'defabcd'
:return: 'abcd'
'''
count = 0
length = len(str1)
for sublen in range(length,0,-1):
for start in range(0,length - sublen + 1):
count += 1
substr = str1[start:start+sublen]
if str2.find(substr) > -1:
print('count={} subStringLen:{}'.format(count,sublen))
return substr
else:
return "'{}' and '{}' do not have a common substring".format(str1,str2)
print(findstr(s1,s2))
print(findstr(s3,s2))
print(findstr(s4,s2))
print(findstr(s5,s2))
print(findstr(s6,s2))
输出结果:
count=2 subStringLen:6 #findstr(s1,s2)
abcdef
count=15 subStringLen:1 #findstr(s3,s2)
a
count=37 subStringLen:1 #findstr(s4,s2)
w
count=1 subStringLen:7 #findstr(s5,s2)
defabcd
'j' and 'defabcdoabcdeftw' do not have a common substring #findstr(s6,s2)
永远不要相信用户的输入,一个健壮的代码往往业务功能块代码很少,而对用户输入的验证代码部分越要更严谨,将用户所有的输入都考虑在内。