简体   繁体   中英

Is this implementation of KMP pattern matching algorithm is right?

I am reading about KMP from this link : ( http://www.geeksforgeeks.org/searching-for-patterns-set-2-kmp-algorithm/ ).

I have implemented the KMP other than given in the respective link and it gives the right answer too, can someone please tell me whether this implementation of KMP is right or wrong? If wrong then, then kindly explain for the same.

Below is the implementation by me :

package Algos.patternMatching;

public class KMP {

    public static void main(String[] args) {
        KMPAlgo("ABABDABACDABABCABAB", "ABABCABAB");
    }

    private static void KMPAlgo(String text, String pattern) {      //check whether right or wrong
        int i = 0;
        int j = 0;

        int[] lps = LPS(pattern);

        while (i < text.length() - pattern.length() + 1) {

            while (j < pattern.length() && pattern.charAt(j) == text.charAt(i)) {

                j++;
                i++;
            }

            if (j == pattern.length()) {
                System.out.println(i - j);
            }

            if (j > 0) {
                j = lps[j - 1];
            } else {
                i++;
            }
        }
    }

    private static int[] LPS(String pattern) {
        int len = 0;
        int i = 0;
        int[] lps = new int[pattern.length()];

        lps[0] = 0;
        i++;

        while (i < pattern.length()) {
            if (pattern.charAt(len) == pattern.charAt(i)) {
                len++;
                lps[i] = len;
                i++;
            } else if (len > 0) {
                len = lps[len - 1];
            } else {
                lps[i] = len;
                i++;
            }

        }

        return lps;

    }

}

Yes, I learnt KMP algorithm from the same source too. And your implementation seems 100% right and complete equivalence of the C++ counterpart.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM