#-*- coding:utf-8 -*-
import datetime
def dist(t,tt,m):
if tt==t[m-1]:
return m
else:
index_list = []
for i,c in enumerate(t):
if c==tt:
index_list.append(i)
if len(index_list)==0:
return m
else:
sum = max(index_list)
return (m-1-int(sum))
def BM(s,t,n,m):
i = m-1
if m>n:
print("模式串长度大于主串")
elif m==n:
if s==t:
print("串匹配成功")
else:
print("未找到匹配字符串1")
else:
while i<=n-1:
j = m-1
while j>=0 and s[i]==t[j]:
j = j-1
i = i-1
if j < 0:
print("串匹配成功")
break
else:
k=dist(t,s[i],m)
i = i+k
if __name__ == '__main__':
s = input("请输入主串:")
t = input("请输入模式串:")
n = len(s)
m = len(t)
oldtime = datetime.datetime.now()
x = 1
while x < 10000000:
x = x + 1
BM(s,t,n,m)
newtime = datetime.datetime.now()
print(u'相差:%s微秒' % (newtime - oldtime).microseconds)
print(u'相差:%s秒' % (newtime - oldtime).seconds)
12-08
1464
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
06-06
1712
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
06-03
5428
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)