菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
478
0

BF算法和KMP算法 python实现

原创
05/13 14:22
阅读数 22114

BF算法 

def Index(s1,s2,pos = 0):
    """ BF算法 """
    i = pos
    j = 0
    while(i < len(s1) and j < len(s2)):
        if(s1[i] ==  s2[j]):
            i += 1
            j += 1
        else:
            i = i - j + 1
            j = 0
    if(j >= len(s2)):
        return i - len(s2)
    else:
        return 0

if __name__ == "__main__":
    s1 = "ababcabcacbab"
    s2 = "abcac"
    print(Index(s1,s2))

  KMP算法

# KMP算法

def Index_KMP(s1,s2,pos=0):
    next = get_next(s2)
    i = pos
    j = 0
    while(i < len(s1) and j < len(s2)):
        if(j == -1 or s1[i] == s2[j]):
            i += 1
            j += 1
        else:
            j = next[j]

    if(j >= len(s2)):
        return i - len(s2)
    else:
        return 0

def get_next(s2):
    i = 0
    next = [-1]
    j = -1
    while(i <len(s2)-1):
        if(j == -1 or s2[i] == s2[j]):
            i += 1
            j += 1
            next.append(j)
        else:
            j = next[j]
    return next

if __name__ == "__main__":
    s1 = "acabaabaabcacaabc"
    s2 = "abaabcac"
    print(Index_KMP(s1,s2))

  

发表评论

0/200
478 点赞
0 评论
收藏