因为需要字符串搜索功能所以写了一个方法,我叫它影子搜索,因为一直有个影子在前面“探路”,写完后总觉得有点问题,但是随便测试了几个东西好像又没有问题?先记录把等以后发现问题再说(我没有完整测试请不要随便使用免得出问题),如果测试没有问题,那么至少比暴力搜索次数要少
context = b"ddcaddaabacabaabaaaadaabaaabaadaabaaaaaaaaaadaabaaaaaaaaaadaaa"
search = b"aaaadaab"
context_p = 0
search_p = 0
shadow_p = 1
shadow_next_p = 0
count = 0
while True:
count += 1
if shadow_p + shadow_next_p >= len(context) or shadow_next_p >= len(search):
pass
elif context[shadow_p + shadow_next_p] == search[shadow_next_p]:
shadow_next_p += 1
else:
shadow_p += 1
shadow_next_p = 0
if context_p >= len(context) or search_p >= len(search):
print("find: %s, for count: %d" % (str(context[context_p - search_p:context_p]), count))
break
elif context[context_p] == search[search_p]:
context_p += 1
search_p += 1
else:
context_p = shadow_p + shadow_next_p
search_p = shadow_next_p
shadow_p += 1
shadow_next_p = 0