常用十大算法(四)— KMP算法


常用十大算法(四)— KMP算法

博客說明

文章所涉及的資料來自互聯網整理和個人總結,意在於個人學習和經驗匯總,如有什么地方侵權,請聯系本人刪除,謝謝!

介紹

KMP是一個解決模式串在文本串是否出現過,如果出現過,最早出現的位置的經典算法

Knuth-Morris-Pratt 字符串查找算法,簡稱為 “KMP算法”,常用於在一個文本串S內查找一個模式串P 的出現位置,這個算法由Donald Knuth、Vaughan Pratt、James H. Morris三人於1977年聯合發表,故取這3人的姓氏命名此算法.

KMP方法算法就利用之前判斷過信息,通過一個next數組,保存模式串中前后最長公共子序列的長度,每次回溯時,通過next數組找到,前面匹配過的位置,省去了大量的計算時間

字符串匹配問題

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

如果當前字符匹配成功(即str1[i] == str2[j]),則i++,j++,繼續匹配下一個字符

如果失配(即str1[i]! = str2[j]),令i = i - (j - 1),j = 0。相當於每次匹配失敗時,i 回溯,j 被置為0。

代碼實現
package com.guizimo;

public class ViolenceMatch {

	public static void main(String[] args) {
		String str1 = "BBC ABCDAB ABCDABCDABDE";
		String str2 = "ABCDABD";
		int index = violenceMatch(str1, str2);
		System.out.println("index=" + index);

	}

	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;
		}
	}
}
KMP算法
  • 得到子串的部分匹配表
  • 使用部分匹配表完成KMP匹配
代碼實現
package com.guizimo;

import java.util.Arrays;

public class KMPAlgorithm {

	public static void main(String[] args) {
		String str1 = "BBC ABCDAB ABCDABCDABDE";
		String str2 = "ABCDABD";
		
		int[] next = kmpNext("ABCDABD"); 
		System.out.println("next=" + Arrays.toString(next));
		
		int index = kmpSearch(str1, str2, next);
		System.out.println("index=" + index); 
	}
	
	//KMP搜索
	public static int kmpSearch(String str1, String str2, int[] next) {
		for(int i = 0, j = 0; i < str1.length(); i++) {
			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) {
		int[] next = new int[dest.length()];
		next[0] = 0;
		for(int i = 1, j = 0; i < dest.length(); i++) {
			while(j > 0 && dest.charAt(i) != dest.charAt(j)) {
				j = next[j-1];
			}
			if(dest.charAt(i) == dest.charAt(j)) {
				j++;
			}
			next[i] = j;
		}
		return next;
	}
}

感謝

尚硅谷

以及勤勞的自己,個人博客GitHub

微信公眾號


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM