很详尽KMP算法

31 篇文章 2 订阅

 

很详尽KMP算法(厉害)

作者:July
时间:最初写于2011年12月,2014年7月21日晚10点 全部删除重写成此文,随后的半个多月不断反复改进。后收录于新书《编程之法:面试和算法心得》第4.4节中。

正文:

https://www.cnblogs.com/ZuoAndFutureGirl/p/9028287.html

 

 

尝试用C生成help / next 数组:

int* getHelpArr(char* s,int help[]){
    if(s==NULL)
        return NULL;
    int slen = length(s);
    help[0]=-1;
    help[1]=0;
    int index = 2;//help数组从第三个元素开始的元素值需要依次推算
    int cn = 0;        //推算help[2]时,help[1]=0,即s[1]之前的字符组成的串中不存在最大匹配前后子串,那么cn作为最大匹配前缀子串的后一个下标自然就是0了
    while(index < slen){
        if(s[index-1] == s[cn]){    //if match[n-1] == match[cn]
            help[index] = help[index-1] + 1;
            index++;
            cn++;
        }else if(help[cn] == -1){    //cn reach 0
            help[index]=0;
            index++;
            cn++;
        }else{
            cn = help[cn];    //set cn to cn' and continue calculate help[index]
        }
    }
    return help;
}

尝试用Python生成help / next 数组:

#using python3

def getHelpArr(s, help):
	slen = len(s)
	help.append(-1) #help[0]
	help.append(0) #help[1]
	index = 2 #help数组从第三个元素开始的元素值需要依次推算
	cn = 0#推算help[2]时,help[1]=0,即s[1]之前的字符组成的串中不存在最大匹配前后子串,那么cn作为最大匹配前缀子串的后一个下标自然就是0了
	while(index < slen):
		if(s[index-1] == s[cn]):  #if match[n-1] == match[cn]
			help.append(help[index-1] + 1)
			index += 1
			cn += 1
			print('branch:%s cn:%d index:%d help:%s' %('1',cn, index, str(help)))
		elif(help[cn] == -1): #cn reach 0
			help.append(0)
			index += 1
			cn += 1
			print('branch:%s cn:%d index:%d help:%s' %('2',cn, index, str(help)))
		else:
			cn = help[cn]	 #set cn to cn' and continue calculate help[index]
			print('branch:%s cn:%d index:%d help:%s' %('3',cn, index, str(help)))

if __name__ == '__main__':
	s = "ABCDABD"
	help = []
	getHelpArr(s, help)
	print("next/help arry:" + str(help))

结果:

>>> 
======== RESTART: C:\Users\Administrator\Desktop\help_next_for_KMP.py ========
branch:2 cn:1 index:3 help:[-1, 0, 0]
branch:3 cn:0 index:3 help:[-1, 0, 0]
branch:2 cn:1 index:4 help:[-1, 0, 0, 0]
branch:3 cn:0 index:4 help:[-1, 0, 0, 0]
branch:2 cn:1 index:5 help:[-1, 0, 0, 0, 0]
branch:3 cn:0 index:5 help:[-1, 0, 0, 0, 0]
branch:1 cn:1 index:6 help:[-1, 0, 0, 0, 0, 1]
branch:1 cn:2 index:7 help:[-1, 0, 0, 0, 0, 1, 2]
next/help arry:[-1, 0, 0, 0, 0, 1, 2]
>>> 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值