1、 KMP模式匹配算法
输入:模式串,主串
功能要求:输出模式串的next值表,输出匹配结果
源码:
1 def matchintg_KMP(t, p, prefix): 2 n, m = len(t), len(p) 3 j, i = 0, 0 4 while j < n and i < m: 5 if i == -1 or t[j] == p[i]: 6 i, j = i + 1, j + 1 7 else: 8 i = prefix[i] 9 if i == m: 10 return j - i 11 return -1 12 13 14 def prefix_table(p): 15 i, k, m = 0, -1, len(p) 16 prefix = [-1] * m 17 while i < m - 1: 18 if k == -1 or p[i] == p[k]: 19 i, k = i + 1, k + 1 20 if p[i] == p[k]: 21 prefix[i] = prefix[k] 22 else: 23 prefix[i] = k 24 else: 25 k = prefix[k] 26 return prefix 27 28 29 if __name__ == '__main__': 30 # t = "ababcabcacbab" 31 # p = "abcac" 32 t = input("请输入主串:") 33 p = input("请输入模式串:") 34 pnext = prefix_table(p) 35 print("模式串next表:", pnext) 36 print("匹配结果:", matchintg_KMP(t, p, pnext))