#include "stdafx.h" #include <cassert> #include <cstdio> #include <cstdlib> #include <iostream> using namespace std; //KMP void NextIndex(const char array[], int len, int next[]) { next[0] = -1; next[1] = 0; for (int i=2; i<len; i++) { int j = next[i-1]; if (array[i-1] == array[j]) { next[i] = j + 1; } else { while (j>=0 && array[i-1] != array[j]) { j = next[j]; } if (j < 0) { next[i] = 0; } else { next[i] = j +1; } } } } int CountKmp(const char* str, int len, const char* substr, int sublen, const int* next) { assert(len >= sublen); const char* t_substr = substr; for (int i=0; i<len-sublen+1; i++) { int j = 0; for ( j=0; j<sublen; ) { if (str[i] == substr[j]) { i++; j++; continue; } else { j = next[j]; } if (-1 == j) { break; } } if (sublen == j) { return i-sublen; } } return -1; } int _tmain(int argc, _TCHAR* argv[]) { cout << "helloworld" << endl; const char *target = "hello every one!"; char *match = "every"; int *next = new int[strlen(match)]; NextIndex(match, strlen(match), next); cout << CountKmp(target, strlen(target), match, strlen(match), next) << endl; system("pause"); return 0; }