-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKMP.java
More file actions
64 lines (59 loc) · 1.41 KB
/
Copy pathKMP.java
File metadata and controls
64 lines (59 loc) · 1.41 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
import java.util.Scanner;
public class KMP {
public static int[] preProcess(final String s) {
int size = s.length();
int[] result = new int[size];
result[0] = 0;
int j = 0;
//ѭ������
for(int i=1;i<size;i++){
while(j>0 && s.charAt(j) != s.charAt(i)){
j = result[j];
}
if(s.charAt(j) == s.charAt(i)){
j++;
}
//�ҵ�һ������
result[i] = j;
}
return result;
}
private static int Match(String target, String pattern) {
int[] table = preProcess(pattern);
int j = 0;
int i = 0;
while (i < target.length()) {
j = 0;
while(j < pattern.length() && i < target.length()){
if(target.charAt(i + j) == pattern.charAt(j)){
++j;
}
else {
break;
}
}
if (j == pattern.length()) {
return i;
}
else if (j > 0){
i += j - table[j];
}
else {
i += 1;
}
}
return -1;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String target = new String();
String pattern = new String();
Scanner in = new Scanner(System.in);
System.out.println("Please enter the target string:");
target = in.nextLine();
System.out.println("Please enter the pattern string:");
pattern = in.nextLine();
System.out.println("The pattern is in " + Match(target, pattern) + " index of target string");
in.close();
}
}