最长公共字串的 o(n),o(1)空间复杂度python实现

先来n空间复杂度的。第一个函数是用来打印的

def print_substring(index_list,B,maxs):
	for value in index_list:
		strings = []
		for i in range(maxs):
			strings.append(B[value[0]-i])
		strings.reverse()
		print("substring are : %s" %strings)

def substring():
	A= 'china_blue'
	B = 'clues'
	index_list=[]
	maxs = 0
	m = len(A)
	n = len(B)
	log_pre = [0 for j in range(m)] 
	log_now = [0 for j in range(m)] 

	for i in range(n):
		for j in range(m):
			if B[i] == A[j]:
				log_now[j] = log_pre[j-1]+1
			else:
				log_now[j] = 0
		
		log_pre = log_now[:]
		local_maxs = max(log_now)
		if local_maxs>=maxs:
			maxs = local_maxs
			index = (i,log_now.index(maxs),maxs)
			index_list.append(index)


	index_list = list(filter(lambda x:x[-1]==maxs,index_list))	
	print("the length is %d" %maxs)
	print_substring(index_list,B,maxs)

o(1)的思想来自参考文献

def sub_string2():
	index_list=[]
	maxs = 0
	m = len(A)
	n = len(B)
	
	if len(A)>len(B):
		A_hat = A
		B_hat = B
	else:
		A_hat = B
		B_hat = A
	
	for i in range(m+n-1):
		pre = 0
		now = 0
		if i<=n-1:
			for j in range(i+1):
				if B_hat[j] == A_hat[(m-1)-i+j]:
					now = pre+1
					if now>=maxs:
						maxs = now
						index_list.append((j,(m-1)-i+j,maxs))
				else:
					now = 0 
				pre = now
		elif n-1<i and i <m-1:
			for j in range(n):
				if B_hat[j] == A_hat[(m-1)-i+j]:
					now = pre+1
					if now>=maxs:
						maxs = now
						index_list.append((j,(m-1)-i+j,maxs))
				else:
					now = 0
				pre = now
		else:
			for j in range(n -(i-(m-1))):
				if A_hat[j] == B_hat[i-(m-1)+j]:
					now = pre+1
					if now>=maxs:
						maxs = now
						index_list.append((i-m+j+1,j,maxs))
				else:
					now = 0
				pre = now
		

	index_list = list(filter(lambda x:x[-1]==maxs,index_list))	
	print("the length is %d" %maxs)
	print_substring(index_list,B_hat,maxs)

看不懂代码的可以留言交流

参考文献:https://www.cnblogs.com/ider/p/longest-common-substring-problem-optimization.html

猜你喜欢

转载自blog.csdn.net/wqtltm/article/details/81290195