-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKmp.java
More file actions
48 lines (46 loc) · 1.36 KB
/
Kmp.java
File metadata and controls
48 lines (46 loc) · 1.36 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
import java.util.ArrayList;
public class Kmp {
public static ArrayList<Integer> kmp(String regEx, String texte) {
ArrayList<Integer> result = new ArrayList<>();
int[] carryOver = constructCarryOver(regEx);
int i = 0;
int j = 0;
while (i < texte.length()) {
if (regEx.charAt(j) == texte.charAt(i)) {
i++;
j++;
}
if (j == regEx.length()) {
result.add(i - j);
j = carryOver[j - 1];
} else if (i < texte.length() && regEx.charAt(j) != texte.charAt(i)) {
if (j != 0)
j = carryOver[j - 1];
else
i++;
}
}
return result;
}
private static int[] constructCarryOver(String regEx) {
int carryOver[] = new int[regEx.length()];
int len = 0;
int i = 1;
carryOver[0] = 0;
while (i < regEx.length()) {
if (regEx.charAt(i) == regEx.charAt(len)) {
len++;
carryOver[i] = len;
i++;
} else {
if (len != 0)
len = carryOver[len - 1];
else {
carryOver[i] = len;
i++;
}
}
}
return carryOver;
}
}