明耀

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
public class KMP {
    public static void main(String[] args)
    {
        String str="ababxbababcadfdsss";
        String subStr="abcad";
        int[] next=getNext(subStr.toCharArray());
        int p=kmp(next,str.toCharArray(),subStr.toCharArray());
        System.out.println(p);
    }
    public static int[] getNext(char[] c)
    {
        int[] next=new int[c.length];
        next[0]=0;
        for(int i=1,k=0;i<c.length;i++)
        {
            while(k>0&&c[k]!=c[i])
                k=next[k-1];
            if(c[k]==c[i])
                k++;
            next[i]=k;
        }
        return next;
    }
    public static int kmp(int[] next,char[] str,char[] c)
    {
        for(int i=0,p=0;i<str.length;i++)
        {
            while(p>0&&str[i]!=c[p])
                p=next[p-1];
            if(str[i]==c[p])
                p++;
            if(p==c.length)
                return i-c.length+1;
        }
        return -1;
    }

}

 

posted on 2017-08-30 13:36  明耀  阅读(227)  评论(0编辑  收藏  举报