最近学习在字符串匹配时,会用到KMP算法,比BF(暴力)算法性能提高了许多,于是用Java实现了一下。
算法中主要问题就是求得next数组,在这里也出现了可以优化的地方,算法原理讲解很多博客也给出,代码供上。。。
写的不好,请指出问题。
package algorithm;
public class KMR {
/**
* 记m=match.length()
* 此算法为未改进的KMP算法中的求next数组
* next[j]表示array[0]~array[j-1]中真前缀和真后缀相等的最大长度,记为k
* 在求next[j]时,对array[0]~array[j-1]进行了j-1躺搜索
* 算法复杂度为O(m^3)
* */
public static int[] getNext(String match) {
int[] next=new int[match.length()];
next[0]=-1;
int i,j,len;
for(j=1;j<match.length();j++) // 相等子串的从match[0]-match[j-1]查找
{
for( len=j-1;len>=1;len--)
{
for( i=0;i<len;i++) // 依次比较match[0]-match[len-1] 与 match[j-len]-match[j-1]
{