KMP:在主串S中找子串T的位置KMP算法的时间复杂度O(|S|+|T|)。
#define maxn 1000 char s[maxn],t[maxn];//s为主串,t为子串 int net[maxn],l1,l2;//l1为主串长度,l2为子串长度 void get_next() { int i=0,j=-1; net[0]=-1; while(i<l2) { if (j==-1 ||t[i]==t[j]) { ++i,++j; if (t[i]!=t[j]) net[i]=j; //优化next数组 else net[i]=net[j]; } else j=net[j]; } /*for (i=0;i<l2;i++) printf("next[%d]=%d\n",i,next[i]); */ } //返回子串在主串第pos个字符之后的位置 //若不存在则返回0 int KMP(int pos) { int i=pos,j=0; get_next(); //核心部分 while(i<l1&&j<l2) { if (j==-1||s[i]==t[j]) i++,j++; else j=net[j]; } if (j==l2) return i-l2; else return 0; }