KMP字串模式匹配的C實現

2021-04-06 20:42:57 字數 1165 閱讀 1015

申請這個blog很久了,可發的內容少的可憐,又一段時間沒更新了,所以隨便發點湊個數,呵呵。

kmp演算法是字串模式匹配的一種比較好的演算法,此演算法的時間複雜度為o(m+n),其中m為源字串長度,n為目標字串長度,此演算法其實是利用目標字串構造乙個簡單的自動機。因為它由d.e.knuth與v.r.pratt和j.h.morris同時發現,所以人們稱它為 克努特-莫里斯-普拉特操作(簡稱kmp演算法),呵呵,第乙個人非常著名,是我的偶像。

下面列出源**清單,希望對這感興趣的朋友與我交流。

/** author : harly

* date   : 2006-4-24

**/#include

#include

#include

#include

//試驗kmp演算法

int* computenext(const char* pattern);  //計算模式的next陣列

int stringmatch(const char* src, const char* target);//普通的模式匹配函式

void print(int* pint , int num); //輸出pint裡面的元素,num為個數

int stringmatchkmp(const char* src, const char* target);

void main()

else

}if (j == targetlen) index = i - targetlen;

else index = -1;

return index;

}int* computenext(const char* pattern)

next[i] = nexttemp +1;

return next;

}void print(int* pint , int num) //輸出pint裡面的元素,num為個數

}//從字串src中查詢target串,如果找到就返回第乙個匹配地位置,否則返回-1

int stringmatchkmp(const char* src, const char* target)

else

}if (j == targetlen)

else

free(next);

return index;

}

KMP字串模式匹配

1.描述 指標i不回溯的字串模式匹配演算法 include include using namespace std 名稱 計算next陣列函式 描述 用於計算kmp模式匹配演算法的next陣列。該方法已得到修正,可以避免連續相同元素的問題 編寫人 李一帆 引數 patternstring 模式串 引...

KMP字串模式匹配演算法實現

kmp演算法是字串模式匹配演算法中較為高效的演算法之一,其在某次子串匹配母串失敗時並未回溯母串的指標而是將子串的指標移動到相應的位置。嚴蔚敏老師的書中詳細描述了kmp演算法,同時前面的例子中也描述了子串移動位置的陣列實現的演算法。前面你已經實現了子串移動的陣列,現在就來利用該陣列來實現kmp模式匹配...

KMP字串模式匹配演算法實現

給定字串s和匹配串t,請你求出匹配串t在s中第一次正確匹配的索引位置。若匹配失敗則返回0。如題,c 版本的kmp 模版如下 樣例輸入 string str thisisalongstring isa nosubstring subt 樣例輸出 1 5 0 include include includ...