KMP算法

public class KMP_Str {
public static int[] next;
public static int kmp_Match(String s,int pox,String p)
{
next=init_Next(p);
int i=pox,j=0;
int sBounds=s.length();
int pBounds=p.length();
while((i<sBounds)&&(j<pBounds))
{
if(j==-1||s.charAt(i)==p.charAt(j))
{
i++;
j++;
}
else
{

j=next[j];
}
}
if(j==pBounds) return i-pBounds;
else return -1;
}
public static int[] init_Next(String p)
{
int i=0,j=-1;
next=new int[p.length()+1];
next[i]=-1;
next[1]=0;

while(i<p.length())
{
if(j==-1||p.charAt(i)==p.charAt(j))
{
i++;
j++;
next[i]=j;
}
else
j=next[j];
}

return next;
}

}

你可能感兴趣的:(KMP)