1. 程式人生 > >用於字串匹配的KMP演算法

用於字串匹配的KMP演算法

KMP演算法的理解分為兩個部分:

1.如何利用next陣列(最大前後綴長度)匹配字元。
藉助next陣列,原字串的i可以不回移,如果當前字元失配則前模式串的j即可。因為雖然當前s[i]和t[j]失配,但是我們知道j之前的字元是匹配的,只要確定t[0]~t[j-1]的最長前後綴,就可以通過移動j再次匹配s[i]。
http://www.ruanyifeng.com/blog/2013/05/Knuth–Morris–Pratt_algorithm.html這篇文章講的比較清楚。

2.如何求next陣列。
next陣列類似於自己和自己作比較,確定當前字串的最大前後綴長度。
http://www.cnblogs.com/c-cloud/p/3224788.html

這篇文章講的比較清楚。

 

感覺還是沒理解透,過段時間回來繼續看。
自己寫的程式碼,要注意各種情況的判斷,比如null和“”是不一樣的。

 class Solution {
 public:
	 int strStr2(const char* source, const char* target) {
		 if (source==NULL || target==NULL) return -1;
		 int m = strlen(source);
		 int n = strlen(target);
		 if (n==0) return 0;
		 if (m < n) return -1;
		 vector<int> next(n,0);
		 int k = 0;
		 int i = 1;
		 for (i; i < n; i++)
		 {
			 while (k>0 && (target[k] != target[i]))
				 k = next[k-1];
			 if (target[k] == target[i]) k++;
			 next[k] = k;
		 }
		 i = 0;
		 int j = 0;
		 while (i<m)
		 {
			 while (j>0 && (source[i] != target[j]))
				 j = next[j - 1];
			 if (source[i] == target[j]) j++;
			 if (j == n) 
				 return (i - n + 1);
			 i++;
		 }
		 return -1;
	 }
 };