Understanding Knuth-Morris-Pratt Algorithm

后端 未结 4 500
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-13 11:05

Can someone explain this to me? I\'ve been reading about it and it still is hard to follow.

text : ababdbaababa
pattern: ababa

table for ababa is -1 0 0

4条回答
  •  清歌不尽
    2020-12-13 11:42

    A Complete Solution using Java:

    package src.com.recursion;
    /*
     * This Expains the Search of pattern in text in O(n)
     */
    public class FindPatternInText {
        public int checkIfExists(char[] text, char[] pattern) {
            int index = 0;
            int[] lps = new int[pattern.length];
            createPrefixSuffixArray(pattern, lps);
            int i = 0;
            int j = 0;
            int textLength = text.length;
            while (i < textLength) {
                if (pattern[j] == text[i]) {
                    j++;
                    i++;
                }
                if (j == pattern.length)
                    return i - j;
                else if (i < textLength && pattern[j] != text[i]) {
                    if (j != 0) {
                        j = lps[j - 1];
                    } else {
                        i++;
                    }
                }
            }
            return index;
        }
    
        private void createPrefixSuffixArray(char[] pattern, int[] lps) {
            lps[0] = 0;
            int index = 0;
            int i = 1;
            while (i < pattern.length) {
                if (pattern[i] == pattern[index]) {
                    lps[i] = index;
                    i++;
                    index++;
                } else {
                    if (index != 0) {
                        index = lps[index - 1];
                    } else {
                        lps[i] = 0;
                        i++;
                    }
                }
            }
        }
        public static void main(String args[]) {
            String text = "ABABDABACDABABCABAB";
            String pattern = "ABABCABAB";
            System.out.println("Point where the pattern match starts is "
                    + new FindPatternInText().checkIfExists(text.toCharArray(), pattern.toCharArray()));
        }
    }
    

提交回复
热议问题