KMP Python

本文深入解析KMP算法,一种用于搜索字符串的高级算法,它利用有限状态机实现最优时间复杂度O(n)。通过构建模式表和DFA(确定有限自动机),实现快速匹配。实例代码演示了从构建模式表到实际搜索过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

KMP is an advanced algorithm for search an substring in a string.

It mains definite finite states.

The general worst time complexity is O(n), because we need to search the whole string.


code is as follow?

def kmp(pat):
	M = len(pat)
	#R = len(set(pat))
	table = {}
	i = 0
	for char in pat:
		if char not in table:
			table[char] = i
			i += 1
	R = len(table)
	#print table
	dfa = [[0 for j in range(M)] for  i in range(R)]
	dfa[table[pat[0]]][0] = 1
	last = 0
	for j in xrange(1, M):
	 	for c in range(R):
	 		dfa[c][j] = dfa[c][last] ## copy mismatch
	 	dfa[table[pat[j]]][j] = j + 1 ## update new state
	 	last = dfa[table[pat[j]]][last] ## preserve last state
	return dfa, table

def search(txt, pat):
	n = len(txt)
	m = len(pat)
	dfa, table = kmp(pat)
	j = 0
	for i in range(n):
		if txt[i] in table:
			j = dfa[table[txt[i]]][j]
	if j == len(pat):
		return True
	return False



pat = "ABAB"
txt = "ABCAB"
search(txt, pat)

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值