lua实现KMP字符串匹配。

来源:互联网 发布:怎么修改远程桌面端口 编辑:程序博客网 时间:2024/05/22 00:33

串S 串P 然后构建Next数组 代表退回的位置。匹配失败 匹配串就往Next[j-1]+1位置从新开始匹配  如果都回到1了 那就可以i++了 

lua下标为1开始 和C/C++不一样。这俩都是下标0开始的

S={4,3,4,41,46,5}P={3,4,41,46,5} --这里可以试试{3,5,41,46,5} 字符串。可以改的Next={}function makeNext()Next[1]=0;for i=2,5,1 dolocal j=Next[i-1]while(S[i]~=P[j+1] and j>=1)doj=Next[j]endif(S[i]==P[j+1])thenNext[i]=j+1         elseNext[i]=1endendendfunction KMP()makeNext()for now=1,6,1 dolocal i=nowlocal pos=1while(pos<5 and i<6)doif(S[i]==P[pos])theni=i+1pos=pos+1        else  if(pos==1) then i=i+1 else pos=Next[pos-1]+1 endend endif(pos==5 and (i-now)==5)then print("P is sub")returnendendprint("not sub")endKMP()


0 0
原创粉丝点击