1. 程式人生 > 實用技巧 >王道資料結構 (7) KMP 演算法

王道資料結構 (7) KMP 演算法

程式碼 :

// kmp 演算法的實現:
#include <stdio.h>
#include <string.h>
void Next(char*T,int *next){
    int i=1;
    next[1]=0;
    int j=0;
    while (i<strlen(T)) {
        if (j==0||T[i-1]==T[j-1]) {
            i++;
            j++;
            next[i]=j;
        }else{
            j=next[j];
        }
    }
}
int KMP(char * S,char * T){ int next[10]; Next(T,next);//根據模式串T,初始化next陣列 int i=1; int j=1; while (i<=strlen(S)&&j<=strlen(T)) { //j==0:代表模式串的第一個字元就和當前測試的字元不相等;S[i-1]==T[j-1],如果對應位置字元相等,兩種情況下,指向當前測試的兩個指標下標i和j都向後移 if (j==0 || S[i-1]==T[j-1]) { i++; j
++; } else{ j=next[j];//如果測試的兩個字元不相等,i不動,j變為當前測試字串的next值 } } if (j>strlen(T)) {//如果條件為真,說明匹配成功 return i-(int)strlen(T); } return -1; } int main() { int i=KMP("ababcabcacbab","abcac"); printf("%d",i); return 0; }

轉載:

http://data.biancheng.net/view/180.html