https://www.acmicpc.net/problem/1786
1786번: 찾기
첫째 줄에, T 중간에 P가 몇 번 나타나는지를 나타내는 음이 아닌 정수를 출력한다. 둘째 줄에는 P가 나타나는 위치를 차례대로 공백으로 구분해 출력한다. 예컨대, T의 i~i+m-1번 문자와 P의 1~m
www.acmicpc.net




- 알고리즘 : KMP
- 풀이 날짜 : 2023.07.12.
< 풀이 설명 >
해당 문제는 KMP에 추가적인 구현만 하면 된다.
KMP 에 대한 설명은 다음과 같다.
[백준/플래티넘] - 백준 11585: 속타는 저녁 메뉴 [플래티넘 Ⅴ / JAVA]
< 코드 >
더보기
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
static int[] table;
static String text, ptr;
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
text = br.readLine();
ptr = br.readLine();
int len = ptr.length();
table = new int[len];
setTable();
System.out.println(kmp(len));
System.out.println(sb);
}
public static void setTable() {
int i = 0;
// i: 움직(앞), j: 뒤
for (int j = 1; j < ptr.length(); j++) {
while (i > 0 && ptr.charAt(j) != ptr.charAt(i))
i = table[i - 1];
if (ptr.charAt(j) == ptr.charAt(i))
table[j] = ++i;
}
}
public static int kmp(int len) {
int count = 0;
int j = 0;
for (int i = 0; i < text.length(); i++) {
while (j > 0 && text.charAt(i) != ptr.charAt(j))
j = table[j - 1];
if (text.charAt(i) == ptr.charAt(j)) {
if (j == ptr.length() - 1) {
sb.append(i + 2 - len).append(" ");
count++;
j = table[j];
} else j++;
}
}
return count;
}
}
728x90
반응형
'Algorithm > KMP' 카테고리의 다른 글
| 백준 1305: 광고 [플래티넘 Ⅳ / JAVA] (0) | 2023.07.17 |
|---|---|
| 백준 11585: 속타는 저녁 메뉴 [플래티넘 Ⅴ / JAVA] (0) | 2023.07.07 |