kmp.cpp 735 B

12345678910111213141516171819202122232425262728
  1. // Given a string S of length n, the KMP algorithm produces an array pnext
  2. // where pnext[i+1] is the length of the longest substring ending at S[i] which is also a prefix of S
  3. void kmp_pre(char x[], int m, int pnext[]) {
  4. int i,j;
  5. j=pnext[0]=-1;
  6. i=0;
  7. while (i<m) {
  8. while (-1!=j && x[i]!=x[j]) j=pnext[j];
  9. pnext[++i]=++j;
  10. }
  11. }
  12. // x pattern, y text
  13. // answer: first index (starting with 0)
  14. // KMP_Count : # occurences
  15. int pnext[100005];
  16. int KMP(char x[], int m, char y[], int n) { // KMP_Count
  17. int i,j; // int ans = 0;
  18. kmp_pre(x,m,pnext);
  19. i=j=0;
  20. while(i<n) {
  21. while(-1!=j && y[i]!=x[j]) j=pnext[j];
  22. i++; j++;
  23. if (j>=m) {
  24. return i-m; // ans++; j=pnext[j];
  25. }
  26. }
  27. return -1; // return ans;
  28. }