【问题标题】:Is this implementation of KMP pattern matching algorithm is right?KMP模式匹配算法的这种实现是对的吗?
【发布时间】:2017-10-14 08:51:46
【问题描述】:

我正在通过此链接阅读有关 KMP 的信息:(http://www.geeksforgeeks.org/searching-for-patterns-set-2-kmp-algorithm/)。

除了相应链接中给出的以外,我已经实现了 KMP,它也给出了正确的答案,有人可以告诉我这种 KMP 的实现是对还是错?如果错了,那么请解释一下。

下面是我的实现:

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;

    }

}

【问题讨论】:

  • “它也给出了正确的答案”——那么它就是正确的

标签: java algorithm pattern-matching knuth-morris-pratt


【解决方案1】:

是的,我也从同一来源学习了 KMP 算法。而且您的实现似乎 100% 正确且与 C++ 对应物完全等价。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-12
    • 1970-01-01
    • 2016-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-07
    相关资源
    最近更新 更多