标签:kmp
#include <iostream> #include <cstring> #include <cstdlib> using namespace std; const int MAX = 100; int nextVal[MAX]; void get_next(char t[]){ int len = strlen(t); int i=1; int j=0; nextVal[1]=0; while(i < len){ if(j==0 || t[i]==t[j]){ i++; j++; if(t[i]!=t[j]) nextVal[i] = j; else nextVal[i] = nextVal[j]; } else j = nextVal[j]; } } int KMP(char s[],char t[]){ int len_s = strlen(s); int len_t = strlen(t); int i,j; i = 0; j = 0; while(i<len_s && j<len_t){ if(s[i] == t[j]){ i++; j++; }else{ j = nextVal[j]; i++; } if(j == len_t) break; } if(j == len_t) return i-j; else return -1; } int main() { char s[] = {'a','b','a','b','c','a','b','d','\0'}; //char t[] = {'a','b','a','b','c','a','b','d','\0'}; char t[] = {'b','a','\0'}; int kmp; get_next(t); kmp = KMP(s,t); cout<<kmp<<endl; cout << "Hello world!" << endl; return 0; }
标签:kmp
原文地址:http://blog.csdn.net/xd_122/article/details/44756109