|
| 1 | +package famous_algorithm; |
| 2 | + |
| 3 | +import org.junit.Test; |
| 4 | + |
| 5 | +import static org.hamcrest.CoreMatchers.is; |
| 6 | +import static org.junit.Assert.assertThat; |
| 7 | + |
| 8 | +public class KMP_Algorithm { |
| 9 | + |
| 10 | + /* |
| 11 | + TASK |
| 12 | + 장문의 문자열 A가 존재할 때, |
| 13 | + 이 문자열 A 안에 특정 문자열 B가 존재하는지 알 수 있는 방법을 해결한다. |
| 14 | + */ |
| 15 | + |
| 16 | + @Test |
| 17 | + public void test() { |
| 18 | + assertThat(KMP("abcxabcdabcdabcy".toCharArray(), "abcdabcy".toCharArray()), is(true)); |
| 19 | + } |
| 20 | + |
| 21 | + /* |
| 22 | + SOLVE |
| 23 | + Karp-Rabin에서는 한 칸씩 이동하면서 패턴 문자열과 비교해줬다. |
| 24 | + 하지만 이는 비교 과정 중에 발생한 소중한 정보를 버리고 다시 비교하는 것이다. |
| 25 | + kmp는 한 칸씩 이동하는 것이 아니라 몇 칸씩 이동하며 비교하기 때문에 |
| 26 | + karp-rabin 보다 빠르게 탐색이 가능하다. |
| 27 | +
|
| 28 | + 패턴의 접두사와 접미사 그리고 경계라는 것을 사용하여 비교가 필요없는 경우를 필터링해 필요할 때만 비교를 해준다. |
| 29 | + 비교를 한 다음 일치하는 부분의 접두사와 접미사를 비교하여 같은 개수 만큼 이동한다. |
| 30 | + 그리고 경계부터 다시 본문과 비교해준다. |
| 31 | +
|
| 32 | + 매번 접두사와 접미사를 비교하는 것도 비용이므로 |
| 33 | + 접두사와 접미사가 같은 개수에 대한 테이블을 만들어둔다. |
| 34 | + */ |
| 35 | + |
| 36 | + private int[] computeTemporaryArray(char[] pattern) { |
| 37 | + int[] lps = new int[pattern.length]; |
| 38 | + int idx = 0; |
| 39 | + for (int i = 1; i < pattern.length;) { |
| 40 | + if (pattern[i] == pattern[idx]) { |
| 41 | + lps[i] = idx + 1; |
| 42 | + idx++; |
| 43 | + i++; |
| 44 | + } else { |
| 45 | + if (idx != 0) { |
| 46 | + idx = lps[idx - 1]; |
| 47 | + } else { |
| 48 | + lps[i] = 0; |
| 49 | + i++; |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + return lps; |
| 54 | + } |
| 55 | + |
| 56 | + public boolean KMP(char []text, char []pattern){ |
| 57 | + |
| 58 | + int lps[] = computeTemporaryArray(pattern); |
| 59 | + int i=0; |
| 60 | + int j=0; |
| 61 | + while(i < text.length && j < pattern.length){ |
| 62 | + if(text[i] == pattern[j]){ |
| 63 | + i++; |
| 64 | + j++; |
| 65 | + }else{ |
| 66 | + if(j!=0){ |
| 67 | + j = lps[j-1]; |
| 68 | + }else{ |
| 69 | + i++; |
| 70 | + } |
| 71 | + } |
| 72 | + } |
| 73 | + if(j == pattern.length){ |
| 74 | + return true; |
| 75 | + } |
| 76 | + return false; |
| 77 | + } |
| 78 | + |
| 79 | + /* |
| 80 | + REFERENCE |
| 81 | + YOUTUBE : https://www.youtube.com/watch?v=GTJr8OvyEVQ |
| 82 | + GITHUB : https://github.com/mission-peace/interview/blob/master/src/com/interview/string/SubstringSearch.java |
| 83 | + */ |
| 84 | + |
| 85 | +} |
0 commit comments