算法其實很簡單—KMP算法

目錄

1. KMP算法介紹

2. KMP算法最佳應用—字符串匹配問題

3. 思路

4. 代碼實現

4.1 KMP算法實現

4.2 暴力匹配算法實現


1. KMP算法介紹

  1. KMP是一個解決模式串在文本串是否出現過,如果出現過,最早出現的位置的經典算法
  2. Knuth-Morris-Pratt字符串查找算法,簡稱爲“KMP算法”,常用於在一個文本串S內查找一個模式串P的出現位置,這個算法由Donald Knuth、Vaughan Pratt、James H. Morris三人於1977年聯合發表,故取這3人的姓氏命名此算法.
  3. KMP方法算法就利用之前判斷過信息,通過一個next數組, 保存模式串中前後最長公共子序列的長度,每次回溯時,通過next數組找到,前面匹配過的位置,省去了大量的計算時間
  4. 參考資料: https://www.cnblogs.com/ZuoAndFutureGirl/p/9028287.html

2. KMP算法最佳應用—字符串匹配問題

  1. 有一個字符串str1= "BBC ABCDAB ABCDABCDABDE",和一個子串str2="ABCDABD"
  2. 現在要判斷str1是否含有str2,如果存在,就返回第一次出現的位置,如果沒有,則返回-1
  3. 要求:使用KMP算法完成判斷,不能使用簡單的暴力匹配算法.

3. 思路

  1. 先得到子串的部分匹配表

“部分匹配值”就是”前綴”和”後綴”的最長的共有元素的長度。以”ABCDABD”爲例,

  • ”A”的前綴和後綴都爲空集,共有元素的長度爲0;
  • ”AB”的前綴爲[A],後綴爲[B], 共有元素的長度爲0;
  • ”ABC”的前綴爲[A, AB],後綴爲[BC, C],共有元素的長度0;
  • ”ABCD"的前綴爲[A, AB, ABC],後綴爲[BCD, CD,D],共有元素的長度爲0;
  • ”ABCDA"的前綴爲[A, AB, ABC, ABCD], 後綴爲[BCDA, CDA, DA,A], 共有元素爲”A”,長度爲1;
  • ”ABCDAB”的前綴爲[A, AB, ABC, ABCD, ABCDA],後綴爲[BCDAB, CDAB, DAB, AB, B],共有元素爲”AB",長度爲2;
  • ”ABCDABD"的前綴爲[A, AB, ABC, ABCD, ABCDA, ABCDAB],後綴爲[BCDABD, CDABD, DABD, ABD, BD, D],共有元素的長度爲0。

 

2. 使用部分匹配表完成KMP

4. 代碼實現

4.1 KMP算法實現

package com.example.datastructureandalgorithm.violence;

import java.util.Arrays;

/**
 * @author 浪子傑
 * @version 1.0
 * @date 2020/6/11
 */
public class KMPDemo {

    public static void main(String[] args) {
        String str1 = "BBC ABCDAB ABCDABCDABDE";
        String str2 = "ABCDABD";

        int[] next = kmpNext(str2);
        System.out.println(Arrays.toString(next));
        System.out.println(kmpSearch(str1, str2, next));
    }

    /**
     * KMP算法查找
     *
     * @param str1
     * @param str2
     * @param next
     * @return
     */
    public static int kmpSearch(String str1, String str2, int[] next) {
        for (int i = 0, j = 0; i < str1.length(); i++) {
            // TODO 此處暫時無非理解~~
            while (j > 0 && str1.charAt(i) != str2.charAt(j)) {
                j = next[j - 1];
            }
            if (str1.charAt(i) == str2.charAt(j)) {
                j++;
            }

            if (j == str2.length()) {
                return i - j + 1;
            }
        }
        return -1;
    }

    /**
     * 獲取字符串的部分匹配表
     *
     * @param str
     * @return
     */
    public static int[] kmpNext(String str) {
        // 創建返回的數組
        int[] next = new int[str.length()];
        next[0] = 0;
        // 循環字符串進行比較
        for (int i = 1, j = 0; i < str.length(); i++) {
            // TODO 此處暫時無非理解~~
            while (j > 0 && str.charAt(i) != str.charAt(j)) {
                j = next[j - 1];
            }
            if (str.charAt(i) == str.charAt(j)) {
                j++;
            }
            next[i] = j;
        }
        return next;
    }
}

4.2 暴力匹配算法實現

package com.example.datastructureandalgorithm.violence;

/**
 * @author 浪子傑
 * @version 1.0
 * @date 2020/6/10
 */
public class ViolenceMatch {

    public static void main(String[] args) {
        String s1 = "我愛你中國親愛的母親,親愛的母親";
        String s2 = "愛的母";
        System.out.println(violenceMatch(s1,s2));
    }

    public static int violenceMatch(String str1, String str2) {
        char[] s1 = str1.toCharArray();
        char[] s2 = str2.toCharArray();

        int s1Len = s1.length;
        int s2Len = s2.length;

        int i = 0;
        int j = 0;
        while (i < s1Len && j < s2Len) {
            if (s1[i] == s2[j]) {
                i++;
                j++;
            } else {
                i = i - j + 1;
                j = 0;
            }
        }
        if (j == s2Len) {
            return i - j;
        } else {
            return -1;
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章