字符串搜索方法(記錄)

因爲需要字符串搜索功能所以寫了一個方法,我叫它影子搜索,因爲一直有個影子在前面“探路”,寫完後總覺得有點問題,但是隨便測試了幾個東西好像又沒有問題?先記錄把等以後發現問題再說(我沒有完整測試請不要隨便使用免得出問題),如果測試沒有問題,那麼至少比暴力搜索次數要少

 

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章