朴素模式匹配与KMP模式匹配算法的Python实现

  1. 朴素模式匹配算法
sLen = len(s)
pLen = len(p)
i,j = 0,0
while (i<sLen and j<pLen):
    if s[i] == p[j]:
        i += 1
        j += 1
    else:
        i = i -j + 1
        j = 0
if (j == pLen):
    return i - j
else:
    return -1
  1. KMP模式匹配算法
def get_next(P):
    P_length = len(P)  # P:模式串
    k, j = -1, 0
    next = [-1 for x in range(P_length)]
    while j < P_length - 1:
        # P[k]表示前缀,P[j]表示后缀
        if k == -1 or P[j] == P[k]:
            k += 1
            j += 1
            if (P[j] != P[k]):
                next[j] = k
            else:
                next[j] = next[k]
        else:
            k = next[k]
    return next


def KMPsearch(S, P):
    S_length = len(S)  # S:文本串
    P_length = len(P)  # P:模式串
    next = get_next(P)
    print(next)
    i, j = 0, 0
    while i < S_length and j < P_length:
        if j == -1 or S[i] == P[j]:
            i += 1
            j += 1
        else:
            j = next[j]
    if j == P_length:
        return i - j
    else:
        return -1


S = 'BBC ABCDAB ABCDABCDABDE'
P = 'ABCDABD'
result = KMPsearch(S, P)
print(result)

输出:
[-1, 0, 0, 0, -1, 0, 2]
15

关于KMP模式匹配算法的详细解释请移步:https://blog.csdn.net/v_july_v/article/details/7041827

你可能感兴趣的:(Python,算法)