#include <iostream> #include<stdio.h> #include<string.h> #define maxn 100 using namespace std; int next[100]; char subStr[]="asdasdasddsasaaaasds"; char str[]="asdasdasdasddsasaaaasdsalsjlasdjalsdasdasdasddsasaaaasds"; //求next数组 void getNext() { int j,k; int len=strlen(subStr); next[0]=-1; j=0; k=-1; while(j<(len-1)) { if(-1==k || subStr[j]==subStr[k]) { j++; k++; next[j]=k; } else { k=next[k]; } } for(int i=0;i<len;i++) { printf("%d\t",next[i]); } } int KMP() { int i=0,j=0; while(i<strlen(str)) { if(-1==j || str[i]==subStr[j]) { j++; i++; } else { j=next[j]; } if(j==strlen(subStr)) return i-strlen(subStr); } return -1; } int main() { getNext(); int pos = KMP(); printf("\t%d\t",pos); return 0; }