-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathKMP.java
More file actions
66 lines (62 loc) · 1.14 KB
/
Copy pathKMP.java
File metadata and controls
66 lines (62 loc) · 1.14 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package KMP;
public class KMP
{
public static int[] preProcess(char[] B)
{
int size = B.length;
int[] P = new int[size];
P[0] = 0;
int j = 0;
for(int i=1;i<size;i++)
{
while(j>0 && B[j]!=B[i])
{
j = P[j];
}
if(B[j] == B[i])
{
j++;
}
P[i] = j;
}
return P;
}
public static void kmp(String parStr,String subStr)
{
int subSize = subStr.length();
int parSize = parStr.length();
char[] B = subStr.toCharArray();
char[] A = parStr.toCharArray();
int[] P = preProcess(B);
System.out.println("P 的列表如下:");
for(int single:P)
{
System.out.println("single = " + single);
}
System.out.println("//////////////////////////////////////////");
int j=0;
int k=0;
for(int i=0;i<parSize;i++)
{
while(j>0&&B[j]!=A[i])
{
j = P[j-1];
}
if(B[j] == A[i])
{
j++;
}
if(j == subSize)
{
j = P[j-1];
k++;
System.out.printf("Find subString '%s' at %d\n",subStr,i-subSize+1);
}
}
System.out.printf("Totally found %d times for '%s'.\n", k,subStr);
}
public static void main(String[] args)
{
kmp("asdfhkasdsafabcabcdefasdfhasdf", "abcabcdef");
}
}