字符串搜索方法(记录)

因为需要字符串搜索功能所以写了一个方法,我叫它影子搜索,因为一直有个影子在前面“探路”,写完后总觉得有点问题,但是随便测试了几个东西好像又没有问题?先记录把等以后发现问题再说(我没有完整测试请不要随便使用免得出问题),如果测试没有问题,那么至少比暴力搜索次数要少

 

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值