forked from christine-1017/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKMPAlgorithm.java
More file actions
62 lines (53 loc) · 1.33 KB
/
KMPAlgorithm.java
File metadata and controls
62 lines (53 loc) · 1.33 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
import java.util.Arrays;
public class KMPAlgorithm {
public static void main(String[] args) {
KMPAlgorithm kmp = new KMPAlgorithm();
String text = "ABDABCCCABDABDABCB";
String pattern = "ABDABC";
kmp.matchString(text, pattern);
}
public int[] getHelperArray(String pattern){
int i = 1, //suffix
j = 0, //prefix
len = pattern.length();
int[] helper = new int[len];
helper[0] = 0;
while(i < len){
if(pattern.charAt(i) == pattern.charAt(j)){
j++;
helper[i] = j;
i++;
}else{
if(j != 0) j = helper[j-1];
else{
helper[i] = 0;
i++;
}
}
}
System.out.println(Arrays.toString(helper));
return helper;
}
public void matchString(String text, String pattern){
if(text == null || pattern == null || (text.length() < pattern.length())) return;
if(pattern.equals("")) return;
int[] helper = getHelperArray(pattern);
int i = 0,
j = 0,
textLen = text.length(),
patternLen = pattern.length();
while(i < textLen && j < patternLen){
if(text.charAt(i) == pattern.charAt(j)){
j++;
i++;
}
if(j == patternLen){
System.out.println("Found pattern at index: " + (i-patternLen));
j = helper[j-1];
}else if((i < textLen && j < patternLen) && text.charAt(i) != pattern.charAt(j)){
if(j != 0) j = helper[j-1];
else i++;
}
}
}
}