KMA算法实现
/**
* KMA字符串匹配算法
* @author KeXin
*
*/
public class Test{
public static int[] ComputePrefix(String p){
char[] P = p.toCharArray();
int m = P.length;
int[] t = new int[m];
t[0] = 0;
int k = 0;
for(int q = 1;q<m;q++){
while(k>0&&P[k]!=P[q])
k = t[k];
if(P[k]==P[q])
k = k+1;
t[q] = k;
}
return t;
}
public static void KMA(String t,String p){
char[] P = p.toCharArray();
char[] T = t.toCharArray();
int n = T.length;
int m = P.length;
int[] pai = ComputePrefix(p);
for(int i = 0;i<m;i++)
System.out.print(pai[i]+"\t");
System.out.println();
int q = 0;
for(int i = 0;i<n;i++){
while(q>0&&P[q]!=T[i])
q = pai[q];
if(P[q]==T[i])
q = q+1;
if(q==m){
System.out.println("Matches in "+(i-m+1));
q = 0;
}
}
}
public static void main(String[] args) {
// String p = "ababaca";
// String t = "aaababacaaaababacab";
String p = "ab";
String t = "abcabcabdabeba";
KMA(t,p);
}
}