KMP算法实现

来源:互联网 发布:建筑设计模型制作软件 编辑:程序博客网 时间:2024/06/03 18:33

关于KMP算法网上已经有了很详细的解释,这里我不在解释,直接用Java写出KMP算法的实现代码供读者参考;

import java.util.*;public class KMP {    public static int kmp(String str,String match){    if(str==null || match==null || match.length()<1 || str.length()<match.length())return -1;    int next[]=getNextArray(match);    int sp=0,mp=0;    while(sp<str.length() && mp<match.length()){    if(str.charAt(sp)==match.charAt(mp)){    sp++;    mp++;    } else if(next[mp]==-1){    sp++;    }else {    mp=next[mp];    }    }    return mp==match.length()?sp-mp:-1;    }        public static int[] getNextArray(String match){    int next[]=new int[match.length()];        next[0]=-1;    if(match.length()==1)return next;    next[1]=0;    int pos=2;    int cn=0;    while(pos<next.length){    if(match.charAt(cn)==match.charAt(pos-1))    next[pos++]=++cn;    else if(cn>0)    cn=next[cn];    else     next[pos++]=0;    }    return next;    }public static void main(String[] args) {// TODO 自动生成的方法存根         Scanner scan=new Scanner(System.in);         String str=scan.nextLine();         String match=scan.nextLine();         System.out.println(kmp(str,match));}}

测试样例:

abcdefg
bc
1

0 0
原创粉丝点击