/**
* 时间复杂度,生成next数组是O(m), 搜索是O(n),整体是O(m+n).
*
*/
public class KMP {
public int find(char[] s, char[] t){
assert(true);
int[] next = getNextArray(t);
int i = 0;
int j = 0;
while((i<s.length)){
if(s[i] == t[j]){
i++;
j++;
if(j == t.length){
return i-j;
}
}else{
j = next[j];
if(j == -1){
i++;
j = 0;
}
}
}
return -1;
}
public int[] getNextArray(char[] t){
assert(true);
int[] next = new int[t.length];
next[0] = -1;
int i=0;
while(i < t.length-1){
next[i+1] = getNext(t, next, i, i);
i++;
}
return next;
}
/**
* @param t 模式字符串
* @param next next数组
* @param pCurrent 当前待匹配位置
* @param p 已知next位置
* @return 下一个位置的值,next[p+1]
*/
private int getNext(char[] t, int[] next, int pCurrent, int p){
int current = next[pCurrent];
if(current == -1){
return 0;
}
if(t[p] == t[current]){
return current + 1;
}else{
return getNext(t, next, current, p);
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
char[] s = "abababc".toCharArray();
char[] t = "ababc".toCharArray();
KMP kmp = new KMP();
int p = kmp.find(s, t);
System.out.println(p);
Tools.printArray(kmp.getNextArray(t));
}
}
KMP
最新推荐文章于 2024-11-16 09:45:51 发布