KMP算法
public class KMP {
public static int[] getNext(String t) {
char p[]=t.toCharArray();
int next[]=new int[p.length];
next[0]=-1;
int j=0,k=-1;
while(j<p.length-1){
if(k==-1||p[j]==p[k]){
j++;
k++;
if(p[j]==p[k])
{
next[j]=next[k];
}else {
next[j]=k;
}
}else{
k=next[k];
}
}
return next;
}
public static int kmp(String ss,String tt) {
char s[]=ss.toCharArray();
char t[]=tt.toCharArray();
int i=0,j=0;
int next[]=getNext(tt);
while(i<s.length&&j<t.length){
if(j==-1||s[i]==t[j]){
i++;
j++;
}else{
j=next[j];
}
}
if(j==t.length){
return i-j;
}else {
return -1;
}
}
public static void main(String[] args) {
System.out.println(kmp("helloworld","low"));
}
}
- 时间复杂度:
O
(
m
+
n
)
O(m+n)
O(m+n)
- 参考文章