首页 > 编程语言 > 详细

KMP Python

时间:2015-03-25 09:00:40      阅读:236      评论:0      收藏:0      [点我收藏+]

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)

 

KMP Python

原文:http://blog.csdn.net/hyperbolechi/article/details/44613763

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!