From b696b8f6779ab3924d37f24961f206442a6269d5 Mon Sep 17 00:00:00 2001 From: HeeEul Shin <83682424+ShinHeeEul@users.noreply.github.com> Date: Wed, 26 Feb 2025 15:16:02 +0900 Subject: [PATCH] =?UTF-8?q?[20250226]=20BOJ=20/=20=ED=94=8C=EB=9E=985=20/?= =?UTF-8?q?=20=EC=B0=BE=EA=B8=B0=20/=20=EC=8B=A0=ED=9D=AC=EC=9D=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../26 BOJ P5 \354\260\276\352\270\260.md" | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 "ShinHeeEul/202502/26 BOJ P5 \354\260\276\352\270\260.md" diff --git "a/ShinHeeEul/202502/26 BOJ P5 \354\260\276\352\270\260.md" "b/ShinHeeEul/202502/26 BOJ P5 \354\260\276\352\270\260.md" new file mode 100644 index 00000000..088ef8b0 --- /dev/null +++ "b/ShinHeeEul/202502/26 BOJ P5 \354\260\276\352\270\260.md" @@ -0,0 +1,69 @@ +```java +import java.io.*; +import java.util.*; + +public class Main { + + static int[] failure; + static int count = 0; + static int pLength; + static int tLength; + static StringBuilder sb; + + public static void main(String[] args) throws IOException { + // TODO Auto-generated method stub + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + char[] T = br.readLine().toCharArray(); + char[] P = br.readLine().toCharArray(); + + pLength = P.length; + tLength = T.length; + + failure = new int[P.length]; + sb = new StringBuilder(); + failureFunction(P); + KMP(T, P); + + System.out.println(count); + System.out.println(sb); + } + + public static void failureFunction(char[] s) { + + int pIdx = 0; + + for(int index = 1; index < pLength; index++) { + + while(pIdx != 0 && s[index] != s[pIdx]) pIdx = failure[pIdx - 1]; + + if(s[pIdx] == s[index]) { + pIdx++; + failure[index] = pIdx; + } + } + + } + + public static void KMP(char[] t, char[] p) { + int pIdx = 0; + + for(int index = 0; index < tLength; index++) { + + while(pIdx != 0 && t[index] != p[pIdx]) pIdx = failure[pIdx - 1]; + + if(t[index] == p[pIdx]) { + if(pIdx == pLength - 1) { + sb.append(index - pLength + 2).append(" "); + count++; + pIdx = failure[pIdx]; + } else { + pIdx++; + } + } + } + + } + +} +```