Java实现的kmp算法:
public class Kmp {
private String mod;
private int[] next;
public Kmp(String mod)
{
this.mod=mod;
this.next=new int[mod.length()];
this.setNext();
}
private void setNext()
{
int k=-1,j=0;
next[0]=-1;
while(j<mod.length()-1)
{
if(k==-1 || mod.charAt(j)==mod.charAt(k))
{
next[++j]=++k;
}
else k=next[k];
}
}
public boolean match(String str)
{
setNext();
if(str.length()<=mod.length()) return str.equals(mod);
int index=0;
for(int i=0;i<str.length();i++)
{
if(str.charAt(i)==mod.charAt(index)) index++;
else
{
if(next[index]!=-1)
{
index=next[index];
i--;
}
else index=0;
}
if(index==mod.length()-1) return true;
}
return false;
}
}