题目

题目分析

KMP算法
首先是生成next数组
然后就是匹配,已经写过很多次了,写几个需要注意的点
1,next数组,初始化next[0]=-1,next[1]=0,我们从2开始遍历

三种情况的判断
if(match[cur-1]==match[pre])
{
      next[cur++]=++pre;//pre之前的字符算上当前的字符
   //next[cur++]=(pre-0)+1;  pre++; 
}
else if(pre!=0) 
{
     pre=next[pre];
}
else
{
     next[cur++]=0;
}

2,正式匹配的时候,判断条件

if()//匹配的话,一直向前走
{
}else if()//match的还不是空的话
{
    matchi=next[matchi];
}else//match都是空的话
{
     stri++;
}

代码展示

public static int match(String str,String match)
    {
        int stri=0;
        int matchi=0;
        int[] nextArr=getNextArr(match);
        while(stri!=str.length()&&matchi!=match.length())
        {
            if(str.charAt(stri)==match.charAt(matchi))
            {
                stri++;
                matchi++;
            }else if(nextArr[matchi]>=0)
            {
                matchi=nextArr[matchi];
            }
            else
            {
                stri++;
            }
        }

        return matchi==match.length()?stri-matchi:-1;
    }
    /*
    生成next数组
     */
    public static int[] getNextArr(String match)
    {
        if(match.length()==1) return new int[]{-1};
        int[] nextArr=new int[match.length()];
        char[] chas=match.toCharArray();
        nextArr[0]=-1;
        nextArr[1]=0;
        int cur=2;
        int pre=0;
        while(cur!=match.length())
        {
            if(chas[cur-1]==chas[pre])
            {
                nextArr[cur++]=++pre;
            }else if(pre!=0)
            {
                pre=nextArr[pre];
            }else
            {
                nextArr[cur++]=0;
            }
        }
        return nextArr;
    }

学习情况

1次