1. 程式人生 > >【算法】KMP字符串匹配算法

【算法】KMP字符串匹配算法

str 字符 amp mage closed oid () hid aps

【原理】

(1)next數組原理

技術分享圖片

(2)特殊情況的處理(巧妙增設哨兵)

技術分享圖片

(3)遞推法構造next[]表

技術分享圖片

技術分享圖片

【實現代碼】

技術分享圖片
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

const int maxn = 100;
char t[maxn];   //text
char p[maxn];
int next[maxn];

void getNext(){
     int m = strlen(p);
     int j=0;     //"主串指針" 
     next[0
] = -1; int t = -1; //模式串指針 while(j<m-1){ if(t<0 || p[j]==p[t]){ next[++j] = ++t; } else{ t=next[t]; } } } int KMP(){ getNext(); //構造next表 int n = strlen(t), i=0;//文本串長度 int m = strlen(p), j=0; //模式串長度
while(j<m && i<n){ if(j<0 || t[i]==p[j]){ //若匹配,一起前進 i++; j++; } else{ //否則,p右移,t不退回 j=next[j]; } } return i-j; } int main(){ cin >> t; // abcdefgabkdabcdu cin >> p; //
abkdab cout << KMP(); return 0; }
View Code

【參考資料】

鄧俊輝教授數據結構

【算法】KMP字符串匹配算法