数据结构 | Python实现KMP字符串匹配 | 源码和示例

def build_failure_table(pattern):
    m = len(pattern)
    fail_table = [0] * m
    j = 0

    for i in range(1, m):
        while j > 0 and pattern[i] != pattern[j]:
            j = fail_table[j - 1]

        if pattern[i] == pattern[j]:
            j += 1
        fail_table[i] = j

    return fail_table

def kmp_search(text, pattern):
    n = len(text)
    m = len(pattern)
    if m == 0:
        return 0

    fail_table = build_failure_table(pattern)
    j = 0

    for i in range(n):
        while j > 0 and text[i] != pattern[j]:
            j = fail_table[j - 1]

        if text[i] == pattern[j]:
            j += 1

        if j == m:
            # Pattern found at position i - j + 1
            return i - j + 1

    return -1  # Pattern not found in the text

# 示例用法
text = "ABABDABACDABABCABAB"
pattern = "ABABCABAB"
result = kmp_search(text, pattern)

if result != -1:
    print(f"Pattern found at position {result} in the text.")
else:
    print("Pattern not found in the text.")

结果:

Pattern found at position 10 in the text.

你可能感兴趣的:(数据结构,力扣,1024程序员节,数据结构)