/*构造next表*/ int *BuildNextTable(char *psSource) { int *pNext = (int*) malloc(strlen(psSource) * sizeof(int)); //Next[]表 int j = 0; //主串指针 int t = pNext[0] = -1; //模式串指针 while (j < (int) strlen(psSource) - 1) { if (0 > t || psSource[j] == psSource[t]) { //匹配 j++; t++; pNext[j] = (psSource[j] != psSource[t]) ? t : pNext[t]; } else {//失配 t = pNext[t]; } } //while return pNext; } /* * KMP算法 ************************************************************************/ int PatternMatch( char *psSource, char *pNext) { int *next = BuildNextTable(psSource); //构造Next[]表 int i = 0; //主串指针 int j = 0; //模式串指针 while(i < (int) strlen(pNext)) { //自左向右逐个比较字符 if (0 > j ||pNext[i] == psSource[j]) {//若匹配,或psSource已移出最左侧 i++; j++; //则转到下一字符 } else { //否则 j = next[j]; //模式串右移 } if(j >= (int) strlen(psSource)) j=0; } //while free(next); //释放Next[]表 return (i - j); }