-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKMP.java
More file actions
42 lines (36 loc) · 1.09 KB
/
KMP.java
File metadata and controls
42 lines (36 loc) · 1.09 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
package algorithm;
import java.io.*;
public class KMP {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
char[] T = br.readLine().toCharArray();
char[] P = br.readLine().toCharArray();
int n = T.length;
int m = P.length;
int[] table = new int[m];
for (int i = 1, j = 0; i < m; i++) {
while (j != 0 && P[i] != P[j])
j = table[j - 1];
if (P[i] == P[j])
table[i] = ++j;
}
int ans = 0;
for (int i = 0, j = 0; i < n; i++) {
while (j != 0 && T[i] != P[j])
j = table[j - 1];
if (T[i] == P[j])
j++;
if (j == m) {
ans++;
sb.append(i - j + 2).append(" ");
j = table[j - 1];
}
}
System.out.println(ans);
System.out.println(sb);
br.close();
}
}
// ABC ABCDAB ABCDABCDABDE
// ABCDABD