Knuth-Morris-Pratt 字符串查找算法,簡稱爲 “KMP算法”,常用於在一個文本串S內查找一個模式串P 的出現位置,這個算法由Donald Knuth、Vaughan Pratt、James H. Morris三人於1977年聯合發表,故取這3人的姓氏命名此算法。
下面先直接給出KMP的算法流程:
- 假設現在文本串S匹配到 i 位置,模式串P匹配到 j 位置
- 如果j = -1,或者當前字符匹配成功(即S[i] == P[j]),都令i++,j++,繼續匹配下一個字符;
- 如果j != -1,且當前字符匹配失敗(即S[i] != P[j]),則令 i 不變,j = next[j]。此舉意味着失配時,模式串P相對於文本串S向右移動了j - next [j] 位。
- 換言之,當匹配失敗時,模式串向右移動的位數爲:失配字符所在位置 - 失配字符對應的next 值(next 數組的求解會在下文的3.3.3節中詳細闡述),即移動的實際位數爲:j - next[j],且此值大於等於1。
文章詳解參考:https://www.cnblogs.com/ZuoAndFutureGirl/p/9028287.html
代碼:
package cn.algorithm.kmp;
import java.util.Arrays;
/**
* @Author smallmartial
* @Date 2019/7/1
* @Email [email protected]
*/
public class KMPAlgorithm {
public static void main(String[] args) {
String str1 = "BBC ABCDAB ABCDABCDABDE";
String str2 = "ABCDABD";
// String str2 = "BBC";
int[] next = kmpNext("ABCDABD");
System.out.println(Arrays.toString(next));
int index = kmpSearch(str1,str2,next);
System.out.println("index = "+ index);
}
//寫出kmp搜索算法
/**
*
* @param str1 源字符串
* @param str2 子串
* @param next 部分匹配表 是字串對應的部分匹配表
* @return 如果返回-1 則沒有匹配到
*/
public static int kmpSearch(String str1, String str2,int[] next){
//遍歷str1
for (int i = 0,j=0; i <str1.length() ; i++) {
//str1.charAt(i) != str2.charAt(j)
//kmp核心算法
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;
}
//獲取一個字符串的部分匹配值
public static int[] kmpNext(String dest){
//創建一個next數組保存部分匹配值
int[] next = new int[dest.length()];
next[0] = 0;//如果字符串長度爲1 部分匹配值就是0
for (int i = 1 ,j = 0; i < dest.length(); i++) {
//當dest.charAt(i) != dest.charAt(j) 滿足時,我們需要從next[j-1]獲取新的j
//直到我們發現有dest.charAt(i) == dest.charAt(j)成立才退出
while (j>0 && dest.charAt(i) != dest.charAt(j)){
j =next[j-1];
}
//當dest.charAt(i) == dest.charAt(j) 滿足時,部分匹配值就是+1
if (dest.charAt(i) == dest.charAt(j)){
j++;
}
next[i]=j;
}
return next;
}
}