-
Notifications
You must be signed in to change notification settings - Fork 7
/
KMP.txt
52 lines (48 loc) · 915 Bytes
/
KMP.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//KMP算法
public class Kmp {
/**
* @param args
*/
public static void main(String[] args) {
String str = "kkkabcecabc";
String msg = "abc";
int res = Kmp(str,msg);
System.out.println(res);
}
public static int Kmp(String str,String msg){
if(str==null || msg==null){
return -1;
}
int[] next = getNext(msg);
int i = 0, j = 0;
while(i<str.length() && j<msg.length()){
if(j==-1 || str.charAt(i)==msg.charAt(j)){
i++; j++;
}
else{
j = next[j];
}
}
if(j==msg.length()){
return i-j;
}
return -1;
}
public static int[] getNext(String msg){
if(msg==null || msg.length()==0){
return null;
}
int[] arr = new int[msg.length()];
arr[0] = -1;
int i = -1, j =0;
while(j<msg.length()-1){
if(i==-1 || msg.charAt(i)==msg.charAt(j)){
arr[++j] = ++i;
}
else{
i = arr[i];
}
}
return arr;
}
}