标签:
@anthor : qingdujun
KMP算法
#include <stdio.h> #include <string.h> #define MAXSTRLEN 256 typedef struct String { char ch_string[MAXSTRLEN]; int len; }SString; /*保存Next值*/ int Next[MAXSTRLEN]; /*计算Next:注意next计算只和子串有关*/ void GetNext(SString t) { int j,k; k = -1; j = 0; Next[0] = -1; while (j < t.len-1) { if (k == -1 || t.ch_string[j] == t.ch_string[k]) { ++j; ++k; Next[j] = k; } else { k = Next[k]; } } } /*KMP算法*/ int KMPIndex(SString s, SString t) { int i,j,v; i = 0; j = 0; while (i < s.len && j < t.len) { if (j == -1 || s.ch_string[i] == t.ch_string[j]) { ++i; ++j; } else { j = Next[j]; } } if (j >= t.len) { v = i - t.len; } else { v = -1; } return v; } int main(void) { int index; SString s,t; /*主串*/ strcpy(s.ch_string,"abccabc"); s.len = strlen(s.ch_string); /*子串*/ strcpy(t.ch_string,"cca"); t.len = strlen(t.ch_string); /*设置Next*/ GetNext(t); /*KMP算法*/ index = KMPIndex(s,t); printf("index = %d\n",index); return 0; }
标签:
原文地址:http://www.cnblogs.com/qingdujun/p/4437186.html