KMP算法笔记概要算法的实现总结
概要
只要在这里做笔记,我就用java实现一般的kmp算法版本。 有关此算法的说明和理解,请转到本专栏。 如何更好地理解和掌握kmp算法? 上面已经有很多前辈充分说明了。
算法为publicclasskmptest//testpublicstaticvoidmain (string [ ] args ({ string haystack=' aaaabbbababcabaaaabbbb ',needle ) //返回主字符串中子字符串的索引system.out.println(RES ); (//匹配主字符串的主逻辑publicstaticintkmp (字符串混合,字符串新) if ) needle==null|||needle.length==0) int [ ] next=new int [ needle.length (]; int i=0,j=0; 获取下一步(needle,下一步); //system.out.println (arrays.tostring (next ) ); while(IHaystack.Length ) (if ) j==-1|||Haystack.Charat )==needle.charAt(j ) j ) ) I; j; } else { j=next[j]; }if(j==Needle.Length ) ) return i-j; }返回- 1; //整个算法的密钥是生成Next数组的publicstaticvoidgetnext (字符串needle,int[] next ) ) intI=0,j=-1; next[0]=-1; while(Ineedle.Length(-1 ) if ) j==-1|||Needle.Charat(I )==needle.charAt(j ) j ) ) I; j; next[i]=j; } else { j=next[j]; }}}总结不忘初心,精益求精!