标签:style blog class code ext color
算法:
#include<IOSTREAM> using namespace std; #define MAXSIZE 100 void calNext(const char *T,int *next);//T为模式串,next为预判数组 int kmp_match(const char *S,const char *T);//在主串S中寻找模式串T,如果找到返回其位置,否则返回-1。位置从0开始 void calNext(const char *T,int *next) { int n = strlen(T); if(n <= 0) { return; } int j = 0,k = -1; next[0] = -1; while(j < n) { if(k==-1 || T[j]==T[k]) { j++; k++; next[j] = k; }else { k = next[k]; } } } int kmp_match(const char *S,const char *T) { if(S==NULL || T==NULL) { return -1; } int n = strlen(S);//主串长度 int m = strlen(T);//模式串长度 int next[MAXSIZE]; calNext(T,next); int i = 0,j = 0; while(i+m <= n) { for(;i<n&&j<m&&S[i]==T[j];++i,++j); if(j==m) return i-m; j = next[j]; if(j==-1) { j++; i++; } } return -1; }
标签:style blog class code ext color
原文地址:http://blog.csdn.net/chdjj/article/details/24851387