-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMain.java
55 lines (47 loc) Β· 1.53 KB
/
Main.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
51
52
53
54
55
package String.P1786;
import java.io.*;
public class Main {
static StringBuilder sb;
public static void main(String[] args) throws Exception {
System.setIn(new FileInputStream("src/String/P1786/input.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String T = br.readLine();
String P = br.readLine();
if (T.length() < P.length()) {
System.out.println(0);
} else {
sb = new StringBuilder();
System.out.println(kmp(T, P));
System.out.println(sb.toString());
}
}
static int[] makePk(String P) {
int[] Pk = new int[P.length()];
int k = 0;
for (int i = 1; i < P.length(); i++) {
while (k > 0 && P.charAt(i) != P.charAt(k))
k = Pk[k - 1];
if (P.charAt(i) == P.charAt(k))
Pk[i] = ++k;
}
return Pk;
}
static int kmp(String T, String P) {
int[] Pk = makePk(P);
int p_idx = 0, count = 0;
for (int i = 0; i < T.length(); i++) {
while (p_idx > 0 && T.charAt(i) != P.charAt(p_idx))
p_idx = Pk[p_idx - 1];
if (T.charAt(i) == P.charAt(p_idx)) {
if (p_idx == P.length() - 1) {
p_idx = Pk[p_idx];
count ++;
sb.append(i - P.length() + 2).append("\n");
} else {
p_idx ++;
}
}
}
return count;
}
}