| 1 | public class KMPTest { |
| 2 | |
| 3 | static String T, P; |
| 4 | static int N; |
| 5 | static int[] fail; |
| 6 | static StringBuilder match_index; |
| 7 | |
| 8 | public static void main(String[] args) { |
| 9 | |
| 10 | T = "ABABABABBABABABABC"; |
| 11 | P = "ABABABC"; |
| 12 | |
| 13 | N = P.length(); |
| 14 | fail = new int[N]; |
| 15 | makeFail(); // fail 함수 만들기 |
| 16 | |
| 17 | match_index = new StringBuilder(); |
| 18 | System.out.println(kmp()); // kmp 함수 : 문자열 T 안에 패턴 P가 몇 번 나타나는지 찾기 |
| 19 | System.out.print(match_index.toString()); // 패턴이 일치한 시작 인덱스 찾기 |
| 20 | } |
| 21 | |
| 22 | static void makeFail() { |
| 23 | for (int i = 1, j = 0; i < N; i++) { |
| 24 | while (j > 0 && P.charAt(i) != P.charAt(j)) { |
| 25 | j = fail[j-1]; |
| 26 | } |
| 27 | if (P.charAt(i) == P.charAt(j)) { |
| 28 | fail[i] = ++j; |
| 29 | } |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | static int kmp() { |
| 34 | int count = 0; |
| 35 | for (int i = 0, j = 0; i < T.length(); i++) { |
| 36 | while (j > 0 && T.charAt(i) != P.charAt(j)) |
| 37 | j = fail[j-1]; |
| 38 | if (T.charAt(i) == P.charAt(j)) { |
| 39 | if (j == N-1) { // 끝까지 왔음 |
| 40 | j = fail[j]; |
| 41 | count ++; |
| 42 | match_index.append(i-N+2).append("\n"); |
| 43 | } else { |
| 44 | j ++; |
| 45 | } |
| 46 | } |
| 47 | } |
| 48 | return count; |
| 49 | } |
| 50 | } |
nothing calls this directly
no outgoing calls
no test coverage detected