Skip to content

Commit f86d460

Browse files
authored
Merge pull request #186 from AlgorithmWithGod/ShinHeeEul
[20250226] BOJ / 플래5 / 찾기 / 신희을
2 parents a81538b + b696b8f commit f86d460

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class Main {
6+
7+
static int[] failure;
8+
static int count = 0;
9+
static int pLength;
10+
static int tLength;
11+
static StringBuilder sb;
12+
13+
public static void main(String[] args) throws IOException {
14+
// TODO Auto-generated method stub
15+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
16+
17+
char[] T = br.readLine().toCharArray();
18+
char[] P = br.readLine().toCharArray();
19+
20+
pLength = P.length;
21+
tLength = T.length;
22+
23+
failure = new int[P.length];
24+
sb = new StringBuilder();
25+
failureFunction(P);
26+
KMP(T, P);
27+
28+
System.out.println(count);
29+
System.out.println(sb);
30+
}
31+
32+
public static void failureFunction(char[] s) {
33+
34+
int pIdx = 0;
35+
36+
for(int index = 1; index < pLength; index++) {
37+
38+
while(pIdx != 0 && s[index] != s[pIdx]) pIdx = failure[pIdx - 1];
39+
40+
if(s[pIdx] == s[index]) {
41+
pIdx++;
42+
failure[index] = pIdx;
43+
}
44+
}
45+
46+
}
47+
48+
public static void KMP(char[] t, char[] p) {
49+
int pIdx = 0;
50+
51+
for(int index = 0; index < tLength; index++) {
52+
53+
while(pIdx != 0 && t[index] != p[pIdx]) pIdx = failure[pIdx - 1];
54+
55+
if(t[index] == p[pIdx]) {
56+
if(pIdx == pLength - 1) {
57+
sb.append(index - pLength + 2).append(" ");
58+
count++;
59+
pIdx = failure[pIdx];
60+
} else {
61+
pIdx++;
62+
}
63+
}
64+
}
65+
66+
}
67+
68+
}
69+
```

0 commit comments

Comments
 (0)