-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy pathKMPTest.java
50 lines (43 loc) Β· 1.37 KB
/
KMPTest.java
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
public class KMPTest {
static String T, P;
static int N;
static int[] fail;
static StringBuilder match_index;
public static void main(String[] args) {
T = "ABABABABBABABABABC";
P = "ABABABC";
N = P.length();
fail = new int[N];
makeFail(); // fail ν¨μ λ§λ€κΈ°
match_index = new StringBuilder();
System.out.println(kmp()); // kmp ν¨μ : λ¬Έμμ΄ T μμ ν¨ν΄ Pκ° λͺ λ² λνλλμ§ μ°ΎκΈ°
System.out.print(match_index.toString()); // ν¨ν΄μ΄ μΌμΉν μμ μΈλ±μ€ μ°ΎκΈ°
}
static void makeFail() {
for (int i = 1, j = 0; i < N; i++) {
while (j > 0 && P.charAt(i) != P.charAt(j)) {
j = fail[j-1];
}
if (P.charAt(i) == P.charAt(j)) {
fail[i] = ++j;
}
}
}
static int kmp() {
int count = 0;
for (int i = 0, j = 0; i < T.length(); i++) {
while (j > 0 && T.charAt(i) != P.charAt(j))
j = fail[j-1];
if (T.charAt(i) == P.charAt(j)) {
if (j == N-1) { // λκΉμ§ μμ
j = fail[j];
count ++;
match_index.append(i-N+2).append("\n");
} else {
j ++;
}
}
}
return count;
}
}