KMP μκ³ λ¦¬μ¦
- μ λμ¬μ μ λ―Έμ¬μ κ°λ
μ νμνμ¬ 'λ°λ³΅λλ μ°μ°μ μΌλ§λ μ€μΌ μ μλμ§' νλ³νμ¬ λ§€μΉν λ¬Έμμ΄μ λΉ λ₯΄κ² μ ννλ κΈ°λ² (μ°Έκ³ λ§ν¬)
λ¬Έμ μ μ© : SWEA λ¨μ΄κ° λ±μ₯νλ νμ
import java.io.*;
public class λ¨μ΄κ°λ±μ₯νλνμ {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int T = Integer.parseInt(br.readLine());
for (int t = 1; t <= T; t++) {
sb.append("#" + t + " ");
String content = br.readLine();
String word = br.readLine();
int n = content.length();
int m = word.length();
int[] pi = new int[m];
int answer = 0;
int idx = 0;
for (int i = 1; i < m; i++) {
while (idx > 0 && word.charAt(i) != word.charAt(idx))
idx = pi[idx - 1];
if (word.charAt(i) == word.charAt(idx)) {
idx += 1;
pi[i] = idx;
}
}
idx = 0;
for (int i = 0; i < n; i++) {
while (idx > 0 && content.charAt(i) != word.charAt(idx)) {
idx = pi[idx - 1];
}
if (content.charAt(i) == word.charAt(idx)) {
if (idx == m - 1) {
answer++;
idx = pi[idx];
}
else
idx++;
}
}
sb.append(answer + "\n");
}
System.out.println(sb);
}
}